Home>

I am a beginner in programming.
I'm making a recipe sharing site with Rails (5.2.4.4).
I'm having trouble implementing the posting function using fileds_for.

It works until form input and submission are executed.
The child model (Recipe Ingredient, Recipe Step) associated with the parent model (Recipe) is not saved in the DB.

I would be grateful if anyone could help.

After sending, the following message will appear in the terminal.
After that, it seems that only the data of the parent model is saved.
Is it a problem how to write recipe_params?

Unpermitted parameters:: recipe_ingredient,: recipe_step
Corresponding source code

recipes_controller.rb

def new
    @recipe = Recipe.new
    @ recipe.recipe_ingredients.build
    @ recipe.recipe_steps.build
  end
  def create
    recipe = Recipe.new (recipe_params)
    recipe.user_id = current_user.id
    recipe.save
    redirect_to recipe_path (recipe)
  end
  private
  def recipe_params
    params.require (: recipe) .permit (
      : title,: body,: recipe_image,
      recipe_ingredients_attributes: [: id,: ingredient,: quantity,: _destroy],
      recipe_steps_attributes: [: id,: step,: step_image,: _destroy]
      )
  end


recipes/new.erb

       Recipe name 
      <% = f.text_field: title, size: 60, placeholder: "Please enter within 20 characters"%>
         A word 
      <% = f.text_area: body, size: "60x2"%>
         Materials 
      <% = f.fields_for: recipe_ingredient, @ recipe.recipe_ingredients.build do | ingredient |%>
        <% = ingredient.text_field: ingredient%>
        <% = ingredient.text_field: quantity%>
      <% end%>
         How to make 
      <% = f.fields_for: recipe_step, @ recipe.recipe_steps.build do | step |%>
        <% = step.attachment_field: step_image%>
        <% = step.text_area: step%>
      <% end%>
      <% = f.submit'Publish recipe'%>


models/recipe.rb

class Recipe

I would appreciate it if you could point out any incomplete or difficult-to-understand questions.
I look forward to working with you.

  • Answer # 1

    As you can guess, the problem is how to write recipe_params.

      params.require (: recipe) .permit (
          : title,: body,: recipe_image,
          recipe_ingredient: [: ingredient,: quantity],
          recipe_step: [: step,: step_image]
          )

    Try as