dimanche 5 avril 2015

4.2 Without cocoon, simple form or formtastic? Nested Recipe attributes

I struggle with nested forms. There're three classes Recipe, Quantity and Ingredient:



class Recipe < ActiveRecord::Base
belongs_to :user
has_many :quantities
has_many :ingredients, through: :quantities
accepts_nested_attributes_for :quantities

class Quantity < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
accepts_nested_attributes_for :ingredient, :reject_if => :all_blank

class Ingredient < ActiveRecord::Base
has_many :quantities
has_many :recipes, :through => :quantities


Recipe Controller



def new
@recipe = current_user.recipes.build
@quantity = @recipe.quantities.build
end
def create
@recipe = current_user.recipes.build(recipe_params)
if @recipe.save
redirect_to @recipe
else
render 'new'
end
end
private
def recipe_params
params.require(:recipe).permit(
:name,
quantities_attributes: [:id, :amount, :ingredient_id],
)
end


View for recipe#new



<%= form_for @recipe, html: {class: "form-horizontal"} do |f| %>
<li class="control-group">
<%= f.label :name, "Recipe Name", class: "control-label" %>
<div class="controls"><%= f.text_field :name %></div>
</li>
<%= f.fields_for :quantities do |quantity| %>
<%= render 'quantity_fields', f: quantity %>
<% end %>
<%= f.submit %>
<% end %>


_quantity_fields



<%= f.label :amount, "Amount:" %>
<%= f.text_field :amount %>


Here should follow a Select input with content from Ingredient and the POST request should insert the ingredient_id in the column of Quantity.



<%= f.fields_for :ingredient do |quantity_ingredient| %>
<%= quantity_ingredient.text_field :name %>
<% end %>


Any ideas? Thanks!


Aucun commentaire:

Enregistrer un commentaire