Ruby on rails 只属于控制台,而不属于服务器

Ruby on rails 只属于控制台,而不属于服务器,ruby-on-rails,foreign-keys,entity-relationship,models,belongs-to,Ruby On Rails,Foreign Keys,Entity Relationship,Models,Belongs To,我的项目有一个很奇怪的问题。我有两种型号,一种是Link,另一种是Category。我有一个索引视图,其中应该列出所有链接以及相应的类别名称。运行服务器并尝试使用时 <%= link.category.name %> 但是当我打开控制台写下: link = Link.find(1) #there is currently only one link link.category.name 它返回正确的类别名称 以下是我的模型和schema.rb: class Link <

我的项目有一个很奇怪的问题。我有两种型号,一种是Link,另一种是Category。我有一个索引视图,其中应该列出所有链接以及相应的类别名称。运行服务器并尝试使用时

<%= link.category.name %>
但是当我打开控制台写下:

link = Link.find(1) #there is currently only one link
link.category.name 
它返回正确的类别名称

以下是我的模型和schema.rb:

class Link < ActiveRecord::Base
  attr_accessible :category_id, :description, :title, :url, :visible

  belongs_to :category

  scope :visible, lambda { where(visible: true) }
end

这怎么会发生?非常感谢你的帮助

也许我可以帮助其他面临同样问题的人

类别id由一个表单分配给链接,该表单从db查询现有类别

<%= f.select(:category_id, @categories.collect { |c| c.name }) %>

我想要分配的类别的id为1。从下拉菜单中选择类别后,link.category_id为0,应该为1

更新:

我通过以下方法修复了错误的索引:

<%= f.collection_select :category_id, @categories, :id, :name, :prompt => "Select a category" %>
“选择一个类别”%>

您是否可以查看您的所有链接是否都与某个类别关联?e、 g.出于某种原因,是否有一个不是零的类别id?尝试这样做,并告诉我它返回什么:
Link.all.collect(&:category\u id)。include?(nil)
感谢您的快速响应!当我在控制台中执行它时,它返回false。目前数据库中只有一个链接,它有一个正确的类别id。嗯,我不知道。。您可以显示您的查看代码吗?查看索引操作的相关控制器和查看代码会有所帮助。我发现问题,类别id错误。很抱歉我提供了错误的信息。我为这个问题添加了一个解决方案,也许我可以帮助其他面临同样问题的人。非常感谢你的帮助!
ActiveRecord::Schema.define(:version => 20130420070717) do

  create_table "categories", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  add_index "categories", ["id"], :name => "index_categories_on_id"

  create_table "links", :force => true do |t|
    t.string   "title"
    t.text     "description"
    t.string   "url"
    t.integer  "category_id"
    t.boolean  "visible"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  add_index "links", ["category_id"], :name => "index_links_on_category_id"
  add_index "links", ["id"], :name => "index_links_on_id"
end
<%= f.select(:category_id, @categories.collect { |c| c.name }) %>
<%= f.collection_select :category_id, @categories, :id, :name, :prompt => "Select a category" %>