Rails 4嵌套资源,表单,强大的参数

时间:2014-12-19 16:37:35

标签: ruby-on-rails ruby nested-forms strong-parameters

我正在尝试创建一个锻炼跟踪器。我有这些嵌套资源

的routes.rb

resources :days do
  resources :workouts
  resources :meals
end

我的模特看起来很好:

Workout.rb

class Workout < ActiveRecord::Base
  has_many :exercises
  belongs_to :day
end

Day.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

当我尝试创建一个新的锻炼时,问题就出现了。

../视图/训练/ _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

我似乎无法保存:day_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

相反,保存的内容为:day_id

Rails控制台:

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"

HELP?

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 params where empty

1 个答案:

答案 0 :(得分:0)

您的路线设置方式,我假设day_id作为网址传递:

/days/:day_id/workouts

如果是这种情况,那么您无需担心表单中的@day,也不需要担心day_id

中的workout_params

形式:

= 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