一对一关系有问题
我有一些比赛,我想为一场比赛获得一个分数。
我的比赛.rb
has_one :score, :dependent => :destroy
我的分数.rb
belongs_to :match
我的 Scores_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 还很陌生,有什么建议吗?
EDIT
编辑我的代码以匹配 create_score 和 build_score ,似乎有效。但现在我有一些奇怪的行为。
在我的 Score.rb 中
attr_accessible :score1, :score2
但是当我尝试在 matches/show.html.haml 中调用时
= @match.score.score1
我收到一个未知的方法调用或者我根本没有看到任何东西......但是如果我只是调用
= @match.score
我得到一个返回的分数对象(例如#)#
EDIT 2
已解决问题。我正在打电话
分数/new.haml.html
= form_for([@match, @match.create_score])
需要是
= form_for([@match, @match.build_score])
一切都按预期进行。
需要进入 Rails 控制台并获取这些对象才能看到每个 :score1 :score2 为 nil