ruby-on-rails - 一对一 : Undefined method build

标签 ruby-on-rails ruby-on-rails-3

一对一关系有问题

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

我的火柴.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/

相关文章:

ruby-on-rails - Rails 单元测试

ruby-on-rails - Rails 中用户的备用电子邮件地址 - 我将如何验证唯一性,或者我的方法是否不正确?

ruby-on-rails - 登录后更新属性设计

ruby-on-rails-3 - 错误错误的请求行 - 强制 ssl - rails

ruby-on-rails - cookie 之间的 Ruby on Rails 差异[:remember_token] and cookies ["remember_token"]

ruby-on-rails - 如何在 AngularJS 和 Ruby on Rails 中实现功能标志?

ruby-on-rails - simple_format 和 2+ 换行符(\n)

ruby-on-rails - 使用 <%= will_paginate %> 更改每页的元素数

Windows 上的 Mysql2 和 Rails

ruby-on-rails-3 - 使用 capistrano 和 passenger 部署 Rails 应用程序时,应该如何设置用户权限?