我正在尝试创建一个锻炼跟踪器。我有这些嵌套资源
路线.rb
resources :days do
resources :workouts
resources :meals
end
我的模型看起来不错:
锻炼.rb
class Workout < ActiveRecord::Base
has_many :exercises
belongs_to :day
end
日.rb
class Day < ActiveRecord::Base
has_many :workouts
has_many :meals
accepts_nested_attributes_for :workouts, :allow_destroy => true
accepts_nested_attributes_for :meals, :allow_destroy => true
end
问题在于当我尝试创建新的锻炼时。
../views/workouts/_form.html.haml
= form_for([@day, @workout]), html: {class: 'form-horizontal'}) do |f|
= f.input :workout, label: "What did you work out", input_html: { class: "form-control"}
= f.input :mood, label: "How do you feel", input_html: { class: "form-control"}
= f.hidden_field :day_id, value: params[:day_id], input_html: { class: "form-control"}
= f.submit
我似乎无法保存锻炼与锻炼相关联的 :d ay_id,尽管使用强参数来接收它们。
WorkoutsController.rb
private
def workout_params
params.require(:workout).permit(:day_id, :name, :mood)
end
def find_day
@day = Day.find(params[:day_id])
end
相反,保存的内容是 :d ay_id 的 nil
轨道控制台:
Workout id: 11, name: "Hey", mood: "no", day_id: nil, created_at: "2014-12-19 14:53:29", updated_at: "2014-12-19 14:53:29"
帮助?
PS - 我试着做
= form_for([@day, @workout]), as: :foo, html: {class: 'form-horizontal'}) do |f|
= f.input :workout, label: "What did you work out", input_html: { class: "form-control"}
= f.input :mood, label: "How do you feel", input_html: { class: "form-control"}
= f.hidden_field :day_id, value: params[:day_id], input_html: { class: "form-control"}
= f.submit
然后
def workout_params
params.require(:foo).permit(:day_id, :name, :mood)
end
但它只是一直说:foo参数在哪里空
您的路由设置方式,我假设day_id
作为 url 参数传递:
/days/:day_id/workouts
如果是这种情况,那么您无需担心表单中的@day
,也无需担心workout_params
中的day_id
形式:
= form_for @workout, html: {class: 'form-horizontal'}) do |f|
= f.input :workout, label: "What did you work out", input_html: { class: "form-control"}
= f.input :mood, label: "How do you feel", input_html: { class: "form-control"}
= f.submit
控制器:
def create
@workout = @day.workouts.new(workout_params)
....
end
private
def workout_params
params.require(:workout).permit(:name, :mood)
end
def find_day
@day = Day.find(params[:day_id])
end