Ruby on rails 一对一:未定义的方法构建
一对一关系有问题吗 我有几场比赛,我想一场比赛得一分 我的对手.rbRuby on rails 一对一:未定义的方法构建,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,一对一关系有问题吗 我有几场比赛,我想一场比赛得一分 我的对手.rb has_one :score, :dependent => :destroy 我的分数.rb belongs_to :match attr_accessible :score1, :score2 我的分数\u controller.rb def new @match = Match.find(params[:match_id]) @score = @match.score.new end def create @
has_one :score, :dependent => :destroy
我的分数.rb
belongs_to :match
attr_accessible :score1, :score2
我的分数\u 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
= @match.score.score1
我犯的错误
undefined method `new' for nil:NilClass
自从我刚接触RoR以来,我还没有和一对一的关系打过交道,有什么建议吗
编辑
编辑我的代码以匹配create_score和build_score,似乎有效。但是现在我有一种奇怪的行为
在我的分数里.rb
belongs_to :match
attr_accessible :score1, :score2
但是当我尝试在我的matches/show.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
= @match.score.score1
我得到一个未知的方法调用,或者我根本看不到任何东西。。。但如果我打电话
= @match.score
我得到一个返回的score对象(例如#)#
编辑2
解决了这个问题。我在打电话
scores/new.haml.html
= form_for([@match, @match.create_score])
需要
= form_for([@match, @match.build_score])
一切按计划进行
需要进入rails控制台并获取这些对象以查看every:score1:score2为零使用
build
而不是new
:
def new
@match = Match.find(params[:match_id])
@score = @match.build_score
end
以下是这方面的文件:
类似地,在create方法中,执行以下操作:
def create
@match = Match.find(params[:match_id])
@score = @match.create_score(params[:score])
end
这方面的文档:你应该做
匹配。建立分数
。这是因为当您调用score
方法时,它将尝试获取关联,并且由于尚未定义关联,它将返回nil
。然后在nil
上调用build
,这就是它爆炸的原因
有许多
关联方法将一种“代理”对象返回给调用它们返回的对象,因此这就是为什么像posts.comments.build这样的方法有效。的方法属于
,有一个
关联尝试直接获取关联,因此您需要执行构建关联
而不是关联。构建
您可以使用以下示例创建分数
@match.build_score
or
@match.create_score
@RyanBigg,我打错了。修好了,我明白了,是的。我现在更改了它,使它与您的匹配,我建立了\u分数,我创建了\u分数。由于create_score保存了对象(如下面的链接中所述),我应该能够调用@match.score.score1(score有属性:score1,:score2),但即使我应该能够在这个关系中双向调用它们(声明有一个并属于)。对于nil,错误为未定义的方法“score1”:NilClass@cschaeffler,请参阅我在您的答案上发表的评论。您的查看代码可以更简单。因为您正在控制器中设置@score=…
,所以您可以执行以下操作:form_for([@match,@score])
谢谢,但此设置是临时的,不会永远停留在那里;)但是谢谢你的建议。你说的投票圈@Ryan Bigg是什么意思?