nested_form不保存到模型Rails 3 [英] nested_form not saving to model Rails 3

查看:70
本文介绍了nested_form不保存到模型Rails 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我无法将表单数据保存到模型中,但我认为我走在正确的道路上.我有2个模型

I think I am on the right path for the following, though i cannot save the form data to the model. I have 2 models

class Prediction < ActiveRecord::Base
  attr_accessible :home_team, :away_team, :home_score, :away_score, :fixtures_attributes

  has_many :fixtures
  accepts_nested_attributes_for :fixtures
end

class Fixture < ActiveRecord::Base
  attr_accessible :home_team, :away_team, :fixture_date, :kickoff_time

  belongs_to :predictions
end

要创建新的预测记录,我有一个表格,其中包含所有固定装置并预先填充了表格,用户只需在每个团队旁边添加得分即可

To create a new prediction record i have a form that takes all the fixtures and pre populates the form and the user will just add scores next to each team

<%= form_for @prediction do |f| %>
<!-- Gets all fixtures -->
<%= f.fields_for :fixtures, @fixtures<!-- grabs as a collection --> do |ff| %>

<%= ff.text_field :home_team %> VS <%= ff.text_field :away_team %><%= f.text_field :home_score %><%= f.text_field :away_score %><br>

<% end %>
<%= f.submit 'Submit Predictions' %>
<% end %>

然后我让我的控制器来处理new/create动作,我认为这是我可能要摔倒的地方

Then i have my controller to take care of the new/create action, which i think is where i may be falling over

class PredictionsController < ApplicationController

def new
 @prediction = Prediction.new
 @prediction.fixtures.build
 @fixtures = Fixture.all
end

 def create
  @prediction = Prediction.new(params[:prediction])
  @prediction.save
   if @prediction.save
    redirect_to root_path, :notice => 'Predictions Submitted Successfully'
   else
    render 'new'
end
  end
 end

最后是我的路线

resources :predictions
resources :fixtures

所以当我提交表格时我得到了错误

So when i submit the form i get the error

ActiveRecord::RecordNotFound in PredictionsController#create
Couldn't find Fixture with ID=84 for Prediction with ID=

看着正在解析的参数(下面的快照),看起来有些不对劲,因为其中一个home_score和away_score没有通过.

Looking at the params being parsed (snapshot below), something does not look right, for one the home_score and away_score are not being passed through.

{"utf8"=>"✓",
 "authenticity_token"=>"DfeEWlTde7deg48/2gji7zSHJ19MOGcMTxEsQEKdVsQ=",
  "prediction"=>{"fixtures_attributes"=>{"0"=>{"home_team"=>"Arsenal",
 "away_team"=>"Norwich",
 "id"=>"84"},
 "1"=>{"home_team"=>"Aston Villa",
 "away_team"=>"Fulham",
 "id"=>"85"},
 "2"=>{"home_team"=>"Everton",
 "away_team"=>"QPR",
 "id"=>"86"}

当前表单输出

任何建议表示赞赏

谢谢

推荐答案

在预测控制器的新方法中将@fixtures设置为Fixture.all时,您将包括所有固定装置,而不仅仅是属于您的预测的固定装置.将表单的结果传递到创建控制器后,就会有与其他预测相关联的固定装置,这是您报告的错误的来源.也许您想要类似@fixtures = @prediction.fixtures的东西.

When you set @fixtures to Fixture.all in the new method in your prediction controller, you are including every fixture, not just the fixtures belonging to your prediction. When the results of the form are passed to the create controller there are fixtures associated with other predictions being passed in which is the source of the error you have reported. Perhaps you want something like @fixtures = @prediction.fixtures.

您在fields_for块中所做的事情在我看来也很错误.您正在将f.text_field用于home_scoreaway_score输入.这将在每个夹具字段中为预测模型重复相同的表单元素.您将无法从中获得想要的结果.老实说,我正在努力了解这种关联的意义.您能更好地解释它吗?我的怀疑是您的模型没有按照需要的方式进行设置.

What you are doing in the fields_for block also looks fairly wrong to my eyes. You are using f.text_field for your home_score and away_score inputs. This will repeat the same form element for the prediction model in each fixture field. You won't get the result you want from this. To be honest, I'm struggling to understand how this association makes sense. Are you able to explain it a little better? My suspicion is that your models are not quite set up the way you need them to be.

好的,我想我对您现在想要实现的目标有了更好的了解.您正在尝试以一种形式创建许多预测,并从现有固定装置列表中预填充home_team和away_team,对吗?

OK, I think I have a better idea of what you're trying to achieve now. You're trying to create many predictions in one form and prefill the home_team and away_team from a list of existing fixtures, right?

好吧,假设是这样,您肯定会以错误的方式进行处理.您无需在预测模型和夹具模型之间建立多对一的关系(因为您已正确推测).您需要做的是通过遍历灯具的集合并从当前灯具实例填充home_teamaway_team字段来生成表单.您是否真的需要将它们设置为可编辑的文本字段,或者只是将它们放在文本字段中以便它们通过?如果是这样,您可以改用隐藏字段.

Okay, assuming that is so, you're definitely approaching it the wrong way. You don't need a many-to-one relationship between your prediction and fixture models (as you have correctly surmised). What you need to do is generate your form by iterating over the collection of fixtures and populating the home_team and away_team fields from the current fixture instance. Do you actually need these to be editable text fields, or are you just putting them in a text field so they get passed through? If so, you could use hidden fields instead.

现在的问题是,Rails不允许轻易地以一种形式创建多个记录.这不是我以前做过的事情,要使它生效需要花费大量的反复试验,但这是使它实现这一目标的最佳猜测.

The problem now though, is that Rails doesn't easily allow creating multiple records in the one form. It's not something I've done before and it would take me quite a bit of trial-and-error to make it work, but here's a best guess for one way of making it so.

models

class Prediction < ActiveRecord::Base
  attr_accessible :home_team, :away_team, :home_score, :away_score, :fixtures_attributes
end

class Fixture < ActiveRecord::Base
  attr_accessible :home_team, :away_team, :fixture_date, :kickoff_time
end


controller

class PredictionsController < ApplicationController

  def new
    @prediction = Prediction.new
    @fixtures = Fixture.all
  end

  def create
    begin
      params[:predictions].each do |prediction|
        Prediction.new(prediction).save!
      end
      redirect_to root_path, :notice => 'Predictions Submitted Successfully'
    rescue
      render 'new'
    end
  end

end


view

<%= form_tag controller: 'predictions', action: 'create', method: 'post' do %>
  <% @fixtures.each do |fixture| %>
    <%= fixture.home_team %> vs <%= fixture.away_team %>
    <%= hidden_field_tag "predictions[][home_team]", fixture.home_team %>
    <%= hidden_field_tag "predictions[][away_team]", fixture.away_team %>
    <%= text_field_tag "predictions[][home_score]" %>
    <%= text_field_tag "predictions[][away_score]" %><br />
  <% end %>
  <%= submit_tag "Submit predictions" %>
<% end %>

所以从本质上讲,我正在创建一个返回参数数组的表单.在这种情况下,我无法使用模型表单助手.

So essentially I'm creating a form that returns an array of parameters. I can't use the model form helpers in this situation.

解决此问题的一种方法是创建一个具有多个预测的虚拟模型,并使用此模型创建嵌套表单.

One way around this would be to create a dummy model that has_many predictions and create a nested form using this.

无论如何,有很多未经测试的代码可能永远都不会被浏览,所以我现在就把它留在那里.

Anyway, that's a lot of untested code that may never get looked at so I'm going to leave it there for now.

这篇关于nested_form不保存到模型Rails 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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