加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 一对一:未定义的方法构建

发布时间:2020-12-16 20:16:36 所属栏目:百科 来源:网络整理
导读:遇到一对一关系的问题 我有一些比赛,我想有一个比分的比赛. 我的Match.rb has_one :score,:dependent = :destroy 我的score.rb belongs_to :match 我的scores_controller.rb def new@match = Match.find(params[:match_id])@score = @match.score.newenddef
遇到一对一关系的问题

我有一些比赛,我想有一个比分的比赛.

我的Match.rb

has_one :score,:dependent => :destroy

我的score.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

我的路线

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,似乎工作.但现在我有一些奇怪的行为.

在我的分数

attr_accessible :score1,:score2

但是当我尝试在我的比赛/ 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读