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
$(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);
});
});
});
The error looks pretty inconspicuous; I don't think this will answer your question directly, but I'll take a shot anyway to see if it helps:
{"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"
}
I tried to determine whether you're actually making a new ingredient, or calling an existing one.
You're using the following fields:
<%= f.fields_for :ingredient do |fi| %>
<%= fi.hidden_field :id %>
<% end %>
<%= f.hidden_field :ingredient_id, :id => 'ingredient_id' %>
The ingredient_id would suggest you're calling an existing ingredient; the id field suggests you're trying to create a new one. This is probably where the error arises.
- Why are you setting
idfor aningredient?- Why are you then referring to
ingredient_idformeal_ingredient?
I would personally get rid of id for the new ingredient, and make ingredient_id dependent on whether you have a new ingredient (it's set automatically if you create a new nested record).
I would also ensure that ingredient_attributes are only accepted if they're all filled in (which I think you have already):
#app/models/meal_ingredient.rb
class MealIngredient < ActiveRecord::Base
accepts_nested_attributes_for :ingredient, reject_if: :all_blank
end
You don't need to explicitly define id for a nested record:
<%= f.fields_for :ingredient do |fi| %>
# remove ID, you don't need it
<%= fi.text_field :name %>
To manage the ingredient_id vs ingredient_attributes thing, you'll probably have to use JS in the front-end (I'll update an answer with this if required); the backend can be handled by using the following:
#app/models/meal_ingredient.rb
class MealIngredient < ActiveRecord::Base
validate :ingredient_set
private
def ingredient_set
errors.add(:ingredient_id, "Need either a new ingredient, or to select one") unless ingredient && ingredient_id.blank?
end
end
Also, it looks like your strong params need to be tweaked:
def meal_params
params.require(:meal).permit(:name, :picture, :tcarb, :tprot, :tfat, :tkcal, meal_ingredients_attributes: [:ingredient_id, :quantity, ingredient_attributes: [:name, :unit, :carb, :prot, :fat, :_destroy]])
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With