使用隐藏字段设置嵌套资源的属性

时间:2018-05-26 22:07:39

标签: ruby-on-rails one-to-many nested-forms

recipe有很多meal_plans。我有一个表单,尝试为我正在查看的meal_plan创建recipe。我有两个属性,我想为隐藏字段meal_plan设置。这些值在DOM中正确设置,但它们不会保存到数据库中。

配方/ show.html.erb

  <%= form_for [@recipe, MealPlan.new] do |f| %>
    <%= f.hidden_field :status, value: "Upcoming" %>
    <%= f.hidden_field :user_id, value: current_user["uid"] %>
    <%= f.submit "Create Meal Plan" %>
  <% end %>

meal_plan.rb

class MealPlan < ApplicationRecord
  belongs_to :recipe
end

recipe_rb

class Recipe < ApplicationRecord
  has_many :meal_plans, :dependent => :destroy
  accepts_nested_attributes_for :meal_plans
  ...
end

recipes_controller.rb

...
def recipe_params
  params.require(:recipe).permit(
    :name, :link, :ingredients, :image_url,
    meal_plans_params: [:recipe_id, :user_id, :status]
  )
end

meal_plans_controller.rb

class MealPlansController < ApplicationController
  def create
    @recipe = Recipe.find(params[:recipe_id])
    @meal_plan = @recipe.meal_plans.create!(params[:meal_plan_params])

    redirect_to @recipe
  end
end

示例结果

<MealPlan id: 10, recipe_id: 1, user_id: nil, status: nil, created_at: "2018-05-26 21:51:11", updated_at: "2018-05-26 21:51:11"> 

当我在检查器中查看这些字段时,user_idstatus的隐藏字段确实有值。我无法弄清楚为什么这些字段不能保存。

提前致谢!

1 个答案:

答案 0 :(得分:0)

我明白了。看起来我需要在表单中使用<%= form_for([@recipe, @recipe.meal_plans.build]) do |f| %>而不是<%= form_for [@recipe, MealPlan.new] do |f| %>