一对一:未定义的方法构建

csc*_*ler 15 ruby-on-rails ruby-on-rails-3

一对一的关系出了问题

我有一些比赛,我希望得到一个比赛的分数.

我的Match.rb

has_one :score, :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)

我的分数.rb

belongs_to :match
Run Code Online (Sandbox Code Playgroud)

我的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
Run Code Online (Sandbox Code Playgroud)

我的routes.rb

resources :matches do
resources :scores
end
Run Code Online (Sandbox Code Playgroud)

我的分数/ 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
Run Code Online (Sandbox Code Playgroud)

我得到的错误

undefined method `new' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

到目前为止,我还没有处理过一对一的关系,因为我对RoR很新,有什么建议吗?

编辑

编辑我的代码以匹配create_score和build_score,似乎工作.但现在我有一些奇怪的行为.

在我的score.rb

attr_accessible :score1, :score2
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在我的match/show.html.haml中调用时

= @match.score.score1
Run Code Online (Sandbox Code Playgroud)

我得到一个未知的方法调用或者根本没有看到任何东西......但是如果我只是打电话

= @match.score
Run Code Online (Sandbox Code Playgroud)

我得到一个得分对象(例如#)#

编辑2

修复了问题.我在打电话

分数/ new.haml.html

= form_for([@match, @match.create_score])
Run Code Online (Sandbox Code Playgroud)

需要是

= form_for([@match, @match.build_score])
Run Code Online (Sandbox Code Playgroud)

一切都按预期工作.

需要进入rails控制台并获取这些对象以查看每个:score1:score2为零

Ben*_*Lee 26

使用build而不是new:

def new
    @match = Match.find(params[:match_id])
    @score = @match.build_score
end
Run Code Online (Sandbox Code Playgroud)

以下是这方面的文档: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
Run Code Online (Sandbox Code Playgroud)

文档:http://guides.rubyonrails.org/association_basics.html#belongs_to-create_association


Rya*_*igg 8

你应该这样做match.build_score.这是因为当你调用score方法时它将尝试获取关联,并且因为它尚未定义,它将返回nil.然后调用buildnil,这就是为什么它炸毁.

has_many关联方法将一种"代理"对象返回给调用它们返回的对象,所以这就是为什么这样的posts.comments.build工作.方法belongs_tohas_one关联尝试直接获取关联,因此您需要build_association而不是association.build.


san*_*mar 5

您可以使用以下示例创建分数

@match.build_score
or
@match.create_score
Run Code Online (Sandbox Code Playgroud)