一对一:未定义的方法构建 [英] One-to-One: Undefined method build

查看:28
本文介绍了一对一:未定义的方法构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一对一关系有问题

我有一些比赛,我想为一场比赛获得一个分数.

I have some Matches and i want to have one score for a match.

我的 Match.rb

my Match.rb

has_one :score, :dependent => :destroy

我的分数.rb

belongs_to :match

我的分数控制器.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

my scores/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 还很陌生,有什么建议吗?

i haven't worked with one to one relations so far since I'm pretty new to RoR, any suggestions?

编辑

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

edited my code to match create_score and build_score, seems to work. but now i have some kind of strange behavior.

在我的 score.rb 中

in my score.rb

attr_accessible :score1, :score2

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

but when i try to invoke in my matches/show.html.haml

= @match.score.score1

我收到一个未知的方法调用,或者我什么也没看到...但如果我只是调用

i get an unknown method call or i don't see anything at all... but if i just call

= @match.score

我得到一个返回的分数对象(例如#)#

i get an score object returned (e.g. #)#

编辑 2

解决了问题.我在打电话

Fix'd problem. I was calling

scores/new.haml.html

scores/new.haml.html

= form_for([@match, @match.create_score])

必须

= form_for([@match, @match.build_score])

一切都按预期进行.

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

needed to enter rails console and fetch those objects to see every :score1 :score2 was nil

推荐答案

使用 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方法中,这样做:

Similarly, in the create method, do it like this:

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

这篇关于一对一:未定义的方法构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆