我认为我走在正确的道路上,尽管我无法将表单数据保存到模型中。我有 2 个模型
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
为了创建一个新的预测记录,我有一个表格,它包含所有的装置并预先填充表格,用户只需在每个团队旁边添加分数
<%= 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 %>
然后我让我的控制器来处理新/创建操作,我认为这是我可能会摔倒的地方
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
所以当我提交表单时,我得到了错误
ActiveRecord::RecordNotFound in PredictionsController#create
Couldn't find Fixture with ID=84 for Prediction with ID=
查看正在解析的参数(下面的快照),有些东西看起来不正确,因为 home_score 和 away_score 没有通过。
{"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"}
当前输出形式
任何建议表示赞赏
谢谢