0

我的项目中出现了一个非常奇怪的问题。我有两个模型,一个是Link和另一个类别。我有一个索引视图,其中应列出所有链接以及相应的类别名称。当运行的服务器,并尝试使用Belongs_to只能通过控制台识别,而不是服务器

<%= link.category.name %> 

我得到一个错误页面如下:

undefined method `name' for nil:NilClass 

但是当我打开控制台,并写上:

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 

class Category < ActiveRecord::Base 
    attr_accessible :name 

    has_many :links 

end 

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 

这是怎么发生的?非常感谢您的帮助!

+1

你能否看到你的所有链接是否与一个类别绑定?例如由于某种原因,category_id不是零? 尝试做到这一点,并告诉我它返回的是什么:'Link.all.collect(&:category_id).include?(nil)' – Zippie 2013-04-20 08:45:51

+0

感谢您的快速响应!当我在控制台中执行它时,它返回false。目前db中只有1个链接,它有一个正确的category_id。 – Linus 2013-04-20 08:58:04

+0

呵呵,我不知道..你可以展示你的视图代码吗? – Zippie 2013-04-20 09:00:04

回答

0

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

category_id是通过从db中查询现有类别的表单分配给链接的。

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

我想分配的类别有ID = 1后,从下拉菜单中选择类,link.category_id为0,它应该是1

UPDATE:

我修复了错误的索引:

<%= f.collection_select :category_id, @categories, :id, :name, :prompt => "Select a category" %> 
相关问题