一对一关系有问题
我有一些比赛,我想为一场比赛获得一个分数。
我的火柴.rb
has_one :score, :dependent => :destroy
我的分数.rb
belongs_to :match
我的 score_controller.rb
def new
@match = Match.find(params[:match_id])
@score = @match.score.new
end
def create
@match = Match.find(params[:match_id])
@score = @match.score.create(params[:score])
end
我的路线.rb
resources :matches do
resources :scores
end
我的分数/new.html.haml
= form_for([@match, @match.score.build]) do |f|
= f.label :score1
= f.text_field :score1
%br
= f.label :score2
=f.text_field :score2
%br
= f.submit
我得到的错误
undefined method `new' for nil:NilClass
到目前为止,我还没有与一对一的关系合作过,因为我对 RoR 还很陌生,有什么建议吗?
编辑
编辑我的代码以匹配 create_score 和 build_score,似乎有效。但现在我有某种奇怪的行为。
在我的分数.rb
attr_accessible :score1, :score2
但是当我尝试在我的matches/show.html.haml 中调用时
= @match.score.score1
我收到一个未知的方法调用,或者我什么也没看到……但如果我只是调用
= @match.score
我得到一个返回的分数对象(例如#)#
编辑 2
修复的问题。我在打电话
分数/new.haml.html
= form_for([@match, @match.create_score])
需要是
= form_for([@match, @match.build_score])
一切都按预期工作。
需要进入 rails 控制台并获取这些对象以查看每个 :score1 :score2 为零
最佳答案
使用 build
而不是 new
:
def new
@match = Match.find(params[:match_id])
@score = @match.build_score
end
以下是这方面的文档:http://guides.rubyonrails.org/association_basics.html#belongs_to-build_association
同样,在create方法中,这样做:
def create
@match = Match.find(params[:match_id])
@score = @match.create_score(params[:score])
end
文档:http://guides.rubyonrails.org/association_basics.html#belongs_to-create_association
关于ruby-on-rails - 一对一 : Undefined method build,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9498671/