jeudi 5 février 2015

Form including check_box_tag -- params not updating a has-many-through relationship

I'm trying to implement a check_box_tag to stock a Fridge model object with Ingredients; the two models are linked via a has-many-through relationship (FridgeIngredient model). It's worth noting that each Fridge also belongs to a User, which I worry might be causing the issue here in some manner (as this is the only difference I can see from where this code worked for me previously).


I've built a successful list of checkboxes for a has-many-through relationship previously, though it won't work on this occasion. The following form code (adapted for these models) is what worked elsewhere, but now fails to update the Fridge:



<%= form_for(@fridge) do |f| %>

<!-- a debug column for testing -->
<%= f.label :debug %>
<%= f.text_field :debug

<!-- the checkboxes -->
<h2>Add ingredients to your Fridge</h2>
<div>
<% hidden_field_tag "fridge[ingredient_ids][]", nil %>
<% Ingredient.all.each do |ingredient| %>
<%= check_box_tag "fridge[ingredient_ids][]", ingredient.id,
@fridge.ingredient_ids.include?(ingredient.id), id: dom_id(ingredient) %>
<%= label_tag dom_id(ingredient), ingredient.name %><br>
<% end %>
</div>
<%= f.submit "Update" %>
<% end %>


This provides what look to me like the correct params, and the 'Debug' field updates as it should:



fridge: !ruby/hash:ActionController::Parameters
debug: ''
ingredient_ids:
- '1'
- '2'
commit: Update
controller: fridges
action: update
id: '2'


Could it be the @fridge variable is incorrect? It does seem to pick up the correct instance of the Fridge when I've tested it. It's currently:



@fridge = current_user.fridge #using my auth method, and unavailable to


However, when the form is submitted for this project, no Ingredients are added to the Fridge. The has-many-through is working as it should be, and Ingredients can be added and accessed in the Rails console.


Thanks for any help!





Aucun commentaire:

Enregistrer un commentaire