0

I have the following form in my Rails app:

   <%= simple_form_for(@ingredient) do |f| %>
      <%= f.error_notification %>

      <div class="form-inputs">
        ...
        <%= f.hidden_field :recipe, value: @recipe.id %>
      </div>

      <div class="form-actions text-center">
        <%= f.button :submit %>
      </div>
    <% end %>

I have this in my controller:

@recipe = Recipe.find(params[:id])
@ingredient = Ingredient.new
@ingredients = Ingredient.where(user_id: current_user.id, recipe_id: @recipe.id)

And I have tested with byebug that @recipe.id comes out as a number (4 in the instance I am testing).

When the form actually gets rendered, the value is correct: enter image description here

However, when the record is create the ingredient still is created with a recipe_id of nil. Any wisdom as to what's going wrong?

4
  • you are looking at the wrong hidden field. yours is inside the .form-inputs div, just below that selected hidden input Commented Aug 17, 2017 at 18:59
  • @MrYoshiji that is correct and the OP has been updated. Unfortunately, that makes the problem even more vexing! Commented Aug 17, 2017 at 19:04
  • the f.hidden_field :recipe should be f.hidden_field :recipe_id Commented Aug 17, 2017 at 19:05
  • @MrYoshiji YES! Thank you. If you write up an answer I'll happily accept it! Commented Aug 17, 2017 at 19:06

2 Answers 2

1

The f.hidden_field :recipe should be f.hidden_field :recipe_id

Sign up to request clarification or add additional context in comments.

Comments

0

As already answered, you should use f.hidden_field :recipe_id

But I will add a plus, try use like this:

Ingredient controller:

@ingredient = Ingredient.new({:recipe_id => @recipe.id})

In ingredient view:

f.hidden_field :recipe_id

In this way you don't need instantiate recipe in view. This will work for your edit view too! It keep things clear!

1 Comment

Thank you for the answer. However, after updating the OP with the correct form-input, the error persists (where the ingredient is created with the recipe_id of nil) even with the html listing a value of 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.