ruby on rails - Belongs_to only recognized by console, not server -
i've got weird problem project. i've got 2 models, 1 link , other category. i've got index view links should listed, corresponding category names. when running server , trying use
<%= link.category.name %>
i error page following:
undefined method `name' nil:nilclass
but when open console , write:
link = link.find(1) #there 1 link link.category.name
it returns correct category name.
here models , 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) create_table "categories", :force => true |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 |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
how can happen? thank help!
maybe can others facing same issue.
the category_id assigned link form queries existing categories db.
<%= f.select(:category_id, @categories.collect { |c| c.name }) %>
the category wanted assign has id = 1. after selecting category dropdown menu, link.category_id 0, should have been 1.
update:
i fixed wrong index by:
<%= f.collection_select :category_id, @categories, :id, :name, :prompt => "select category" %>
Comments
Post a Comment