I have a has_many through association and I'm getting an error because I'm not passing the :ingredient_id
as an array (or something like that, it's just a guess :) )
Error:Couldn't find Ingredient with ID=1 for MealIngredient with ID=
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"oJQaOCcVavXpWTs4Zz88TWrBchkf7315AnxCJgoYGnpzOxqWd3tz1tiSFwZGDPmzVPpzkSDhFGdDY9j5bpoI1Q==",
"meal"=>{"name"=>"",
"meal_ingredients_attributes"=>{"1450070337804"=>{"ingredient_attributes"=>{"id"=>"1",
"name"=>"Banana"},
"ingredient_id"=>"2", # HERE THE ID IS BEING SENT
"quantity"=>"0.0",
"_destroy"=>"false"},
"1450070339919"=>{"ingredient_attributes"=>{"id"=>"2",
"name"=>"Grape"},
"ingredient_id"=>"", # HERE THERE'S NO ID BEING SENT
"quantity"=>"0.0",
"_destroy"=>"false"}}},
"commit"=>"Create Meal"}
This is how I'm handling this nested form:
Ingredient.rb
class Ingredient < ActiveRecord::Base
has_many :meal_ingredients
has_many :meals, through: :meal_ingredients
accepts_nested_attributes_for :meal_ingredients, :reject_if => :all_blank
end
Meal.rb
class Meal < ActiveRecord::Base
has_many :meal_ingredients
has_many :ingredients, through: :meal_ingredients
accepts_nested_attributes_for :ingredients, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :meal_ingredients
end
MealIngredient.rb
class MealIngredient < ActiveRecord::Base
belongs_to :meal
belongs_to :ingredient
accepts_nested_attributes_for :ingredient, :reject_if => :all_blank
end
_form.html.erb
<div class = "row">
<div class= "col-md-10 col-md-offset-1">
<%= simple_form_for(@meal) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
</div>
<h3>ingredientes</h3>
<fieldset id="ingredients">
<ol>
<%= f.fields_for :meal_ingredients do |meal_ingredient| %>
<%= render "meal_ingredient_fields", :f => meal_ingredient %>
<% end %>
</ol>
<div class="form-actions">
<div><%= link_to_add_association 'adicionar ingrediente', f, :meal_ingredients, 'data-association-insertion-node' => "#ingredients ol", 'data-association-insertion-method' => "append", :wrap_object => Proc.new {|quantity| quantity.build_ingredient; quantity }, :class => "btn btn-default" %></div>
</div>
</fieldset>
<div class="form-actions">
<div><%= f.button :submit, class: "btn btn-success" %></div>
</div>
<% end %>
</div>
</div>
_meal_ingredient_fields.html.erb
<div class = "nested-fields">
<table class= "table">
<thead>
<tr>
<td>
<%= f.label "Nome" %>
</td>
<td>
<%= f.label "Unidade" %>
</td>
<td>
<%= f.label "Carbo" %>
</td>
<td>
<%= f.label "Prot" %>
</td>
<td>
<%= f.label "Gordura" %>
</td>
<td>
<%= f.label "Quantidade" %>
</td>
<td>
<%= f.label "kcal" %>
</td>
</tr>
</thead>
<tbody>
<tr>
<%= f.fields_for :ingredient do |fi| %>
<%= fi.hidden_field :id %> ## EDIT 1: THIS LINE WAS REMOVED
<td scope="row" class="col-md-4">
<%= fi.autocomplete_field :name, autocomplete_ingredient_name_ingredients_path, :id_element => '#ingredient_id', class: "form-control" %>
</td>
<td class="col-md-1">
<%= fi.text_field :unit, required: true, class: "form-control" %>
</td>
<td class="col-md-1">
<%= fi.text_field :carb, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control " %>
</td>
<td class="col-md-1">
<%= fi.text_field :prot, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control " %>
</td>
<td class="col-md-1">
<%= fi.text_field :fat, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control " %>
</td>
<% end %>
<td class="col-md-1">
<%= f.hidden_field :ingredient_id %> ## EDIT 1: FOLLOWING CODE WAS REMOVED: :id => 'ingredient_id'
<%= f.number_field :quantity, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
</td>
<td class="col-md-1">
</td>
<td class="col-md-1">
<%= link_to_remove_association "remove item", f, :class => "btn btn-danger" %>
</td>
</tr>
</tbody>
</table>
</div>
Finally, the controller: meals_controller.rb
class MealsController < ApplicationController
before_action :set_meal, only: [:edit, :update, :show]
def index
@meals = Meal.all
end
def show
end
def new
@meal = Meal.new
@ingredient = @meal.ingredients.build
end
def create
@meal = Meal.new(meal_params)
if @meal.save
flash[:success] = "Refeição criada com sucesso!"
redirect_to meals_path
else
render :new
end
end
def edit
end
def update
if @meal.update(meal_params)
flash[:success] = "Your meal was updated succesfully!"
redirect_to meal_path(@meal)
else
render :edit
end
end
private
def meal_params
params.require(:meal).permit(:name, :picture, :tcarb, :tprot, :tfat, :tkcal, meal_ingredients_attributes: [:ingredient_id, :quantity, ingredient_attributes: [:id, :name, :unit, :carb, :prot, :fat, :_destroy]])
end
def set_meal
@meal = Meal.find(params[:id])
end
end
Please help, this is giving me headaches :D
EDIT
ingredients.js I'm using to gather the current id set by cocoon and apply into the fields when an ingredient is selected in autocomplete.
$(function(){
var num;
var id;
$('#ingredients').on('cocoon:after-insert', function(e, insertedItem) {
$('input[id^="meal_meal_ingredients_attributes_"][id$="_ingredient_attributes_name"]').each(function(){
var current = $(this);
var rx = /meal_meal_ingredients_attributes_(.*)_ingredient_attributes_name/;
num = rx.exec(current.attr('id'))[1];
id = '#meal_meal_ingredients_attributes_'+ num +'_ingredient_';
});
$(id + 'attributes_name').bind('railsAutocomplete.select', function(event, data){
$( id + 'id' ).val( data.item.id);
$( id + 'attributes_unit' ).val( data.item.unit).prop('disabled', true);
$( id + 'attributes_carb' ).val( data.item.carb).prop('disabled', true);
$( id + 'attributes_prot' ).val( data.item.prot).prop('disabled', true);
$( id + 'attributes_fat' ).val( data.item.fat).prop('disabled', true);
});
});
});