Vote count:
0
I'm developing a form that links recipes, recipe_entries (has_many_though join table) and ingredients with jQuery autocomplete in Rails 4. I'm using a combination of of the simple_form, cocoon and rails4-autocomplete gems. The idea is that users can create a recipe and dynamically add and edit associated ingredients via autocomplete (the quantity for each ingredient is stored on the join table).
I have most functionality working, however the only issue that still bugs me is that I had to create an f.input for :ingredient that when editing the recipe shows values, such as # and not the desired name of the associated ingredient.
Other than that, I can dynamically create, delete and update all ingredient associations. Any tips are much appreciated. Here my code:
Gemfile
gem 'rails', '4.0.2'
gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'simple_form'
gem "cocoon"
gem 'rails4-autocomplete'
Recipe.rb
class Recipe < ActiveRecord::Base
has_many :recipe_entries, :dependent => :destroy
has_many :ingredients, through: :recipe_entries
accepts_nested_attributes_for :recipe_entries,:allow_destroy => true
accepts_nested_attributes_for :ingredients
end
RecipeEntry.rb
class RecipeEntry < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
Ingredient.rb
class Ingredient < ActiveRecord::Base
has_many :recipe_entries
has_many :recipes, through: :recipe_entries
end
Recipes form:
<%= simple_form_for(@recipe) do |f| %>
<% if @recipe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>
<ul>
<% @recipe.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.input :name %>
<%= f.input :description %>
<div id="recipe_entries">
<%= f.simple_fields_for :recipe_entries, :input_html => { :class => "form_inline" } do |entry|%>
<% render 'recipe_entry_fields', :f => entry %>
<% end %>
<%= link_to_add_association 'add recipe entry', f, :recipe_entries%>
</div>
<%= f.button :submit %>
<% end %>
recipe_entry_partial
<div class="nested-fields">
<% @it=f.options[:child_index] %>
<%= f.input :ingredient_id, as: :hidden, input_html: {id: "ingredient_id#{@it}"} %>
<%= f.input :ingredient, :url => autocomplete_ingredient_name_recipes_path, :as => :autocomplete, :input_html => {id_element: "#ingredient_id#{@it}"}, placeholder: "Enter ingredient..." %>
<%= f.input :quantity %>
<%= link_to_remove_association "remove entry form", f %>
</div>
Rails 4 - set display value when editing autocomplete nested fields_for
Aucun commentaire:
Enregistrer un commentaire