0
내 프로젝트에 정말 이상한 문제가 있습니다. 나는 2 개의 모델을 가지고 있는데, 하나는 Link이고 다른 하나는 Category입니다. 모든 링크가 나열되어야하는 색인보기가 해당 카테고리 이름과 함께 있습니다. 서버를 실행하고Belongs_to는 서버가 아닌 콘솔에서만 인식합니다.
<%= link.category.name %>
를 사용하려고 할 때 나는 다음과 같이 오류 페이지를 얻을 :
undefined method `name' for nil:NilClass
하지만 콘솔을 열 때 쓰기 :
link = Link.find(1) #there is currently only one link
link.category.name
는 그것은을 반환 올바른 카테고리 이름.
class Link < ActiveRecord::Base
attr_accessible :category_id, :description, :title, :url, :visible
belongs_to :category
scope :visible, lambda { where(visible: true) }
end
: 여기
내 모델 및 schema.rb 있습니다.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
어떻게 될 수 있습니까? 당신의 도움을 주셔서 대단히 감사합니다!
모든 링크가 카테고리에 연결되어 있는지 확인할 수 있습니까? 예 : 어떤 이유로 든 nil이 아닌 category_id가 있습니까? 이 작업을 수행하고 반환하는 내용을 알려주십시오. 'Link.all.collect (& : category_id) .include? (nil)' – Zippie
빠른 응답을 보내 주셔서 감사합니다! 콘솔에서 실행하면 false를 반환합니다. 현재 db에는 단 하나의 링크 만 있으며 올바른 category_id가 있습니다. – Linus
허, 나도 몰라. 당신이보기 코드를 보여줄 수 있겠 니? – Zippie