0
我能夠得到一個模型發佈爲has_many
和accepts_nested_attributes_for
模型類別正常工作。但是,我想限制帖子只有一個類別,這是我失敗的地方。下面是修改後的代碼:Rais 5與nested_attributes has_one關係的錯誤
# post.rb
has_one :category_tag, :dependent => :delete
has_one :category, through: :category_tag
accepts_nested_attributes_for :category_tag
# posts_controller.rb
def new
@post = Post.new
@post.category_tag.build
end
而且^存在的問題是:對無未定義的方法「構建」:NilClass
它工作得很好,我用
TIA
has_many :category_tags
和
@post.category_tags.build
當
我使用導軌5和解決方案SOU對我來說很奇怪,實際上它不工作..'undefined method build_category_tag' –
這很奇怪!我切換回'has_many'設置來繼續處理應用程序的其他方面。然而,當你發佈了答案(哪一個不起作用)時,我再次嘗試原始行(在切換到has_one設置之後)'@ post.category_tag.build',並且它的工作完美無缺。我記得當我嘗試我發佈的內容時,確實重新啓動了服務器(首先應該不是問題)。 –
它應該已經創建。請參閱http://guides.rubyonrails.org/association_basics.html#has-one-association-reference – SteveTurczyn