4

저는 Ruby on Rails를 처음 사용하고 바로 레일 4에서 시작되었습니다.레일 4, 이중 중첩 모델 및 강력한 매개 변수

레시피와 성분 모델을 성공적으로 중첩하여 동일한 형식으로 추가 할 수 있습니다. 다음으로 나는 같은 재료 안에 수량을 추가 할 수 있도록 성분 내에 수량을 중첩시키고 싶습니다. 모든 것이 잘 될 때까지 성분의 양이 데이터베이스에 삽입 될 때까지 그리고 나는 이것으로부터 recipes_controller의 강력한 매개 변수에 문제가 있다고 생각합니다. 하지만 아래에 전체 코드를 게시 할 것입니다. 양식에 simple_form을 사용하고 있습니다.

도움 주시면 감사하겠습니다. 여기

class RecipesController < ApplicationController 

    def new 
    @recipe = Recipe.new 
    3.times do 
     ingredient = @recipe.ingredients.build 
     1.times {ingredient.quantities.build } 
    end 
    end 

    def create 
    @recipe = Recipe.new(params[:recipe].permit(:title, :desc, ingredients_attributes: [:id, :recipe_id, :name, :_destroy, quantities_attributes: [:id, :ingredient_id, :amount, :unit, :_destroy]])) 

    if @recipe.save 
     redirect_to @recipe 
    else 
     render "new" 
    end 
    end 

    def show 
    @recipe = Recipe.find(params[:id]) 
    end 


    def edit 
    @recipe = Recipe.find(params[:id]) 
    end 


    def update 
    @recipe = Recipe.find(params[:id]) 

    if @recipe.update(params[:recipe].permit(:title, :desc)) 
     redirect_to @recipe 
    else 
     render 'edit' 
    end 
    end 


    def destroy 
    @recipe = Recipe.find(params[:id]) 
    @recipe.destroy 

    redirect_to recipes_path 
    end 





    def index 
    @recipes = Recipe.all 
    end 

    private 
    def post_params 
     params.require(:recipe).permit(:title, :desc, ingredients_attributes: [:id, :recipe_id, :name, :_destroy, quantities_attributes: [:id, :ingredient_id, :amount, :unit, :_destroy]]) 
    end 
end 

는 그때 파셜 통해 레시피 성분 및 양에 대한 형태를 만드는 간단한 형태를 사용 recipes_controller이다

class Recipe < ActiveRecord::Base 
    has_many :comments, dependent: :destroy 
    has_many :ingredients, dependent: :destroy 
    accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true 
    validates :title, presence: true 
    validates :desc, presence: true 
end 


class Ingredient < ActiveRecord::Base 
    belongs_to :recipe 
    has_many :quantities, dependent: :destroy 
    accepts_nested_attributes_for :quantities, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true 
end 

class Quantity < ActiveRecord::Base 
    belongs_to :ingredient 
end 

: 여기

내 모델이다.

_form :

_ingredients_fields에서 렌더링
<%= simple_form_for @recipe do |f| %> 
    <%= f.error_notification %> 


    <%= f.input :title %> 
    <%= f.input :desc %> 



    <%= f.simple_fields_for :ingredients do |builder| %> 

    <%= render "ingredient_fields", :f => builder %> 


    <% end %> 

    <p class="links"> 
    <%= link_to_add_association 'add ingredient', f, :ingredients %> 
    <p class="links"> 
    <%= f.error :base%> 
    <%= f.submit %> 

<% end %> 

:

_quantities_fields에서 렌더링
<div class="nested-fields"> 
    <%= f.input :name, label: "Ingredient" %> 



    <%= f.simple_fields_for :quantities do |builder| %> 

    <%= render "quantities_fields", :f => builder %> 

    <% end %> 

    <%= link_to_remove_association "remove", f %> 
</div> 

: [EDITED]

<div class="nested-fields"> 
    <%= f.input :amount %> 
    <%= f.input :unit %> 
</div> 

새로운 레시피를 추가하는 시도가 발생할 다음 로그 진술 :

Started POST "/recipes" for 127.0.0.1 at 2013-10-29 14:15:40 +0100 
Processing by RecipesController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"t6LKgDLwAxaU9xo2ipyCM+j1yfVF9WrI8AoGTX+gRkw=", "recipe"=>{"title"=>"Pancakes", "desc"=>"Tasty", "ingredients_attributes"=>{"0"=>{"name"=>"Milk", "quantities_attributes"=>{"0"=>{"amount"=>"1", "unit"=>"Cup"}}, "_destroy"=>"false"}}}, "commit"=>"Create Recipe"} 
    [1m[35m (0.1ms)[0m begin transaction 
    [1m[36mSQL (3.5ms)[0m [1mINSERT INTO "recipes" ("created_at", "desc", "title", "updated_at") VALUES (?, ?, ?, ?)[0m [["created_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00], ["desc", "Tasty"], ["title", "Pancakes"], ["updated_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00]] 
    [1m[35mSQL (0.4ms)[0m INSERT INTO "ingredients" ("created_at", "name", "recipe_id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00], ["name", "Milk"], ["recipe_id", 27], ["updated_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00]] 
    [1m[36m (7.8ms)[0m [1mcommit transaction[0m 
Redirected to http://www.projectcookbook.dev/recipes/27 
Completed 302 Found in 22ms (ActiveRecord: 11.7ms) 
+0

아마도 [폼 객체 패턴 (https를해야한다. thoughtbot.com/activemodel-form-objects)는 복잡한 ActiveRecord 중첩 속성 문제를 해결하는 좋은 방법입니다. – shvetsovdm

답변

2

_quantities 및 _ingredients partials와 비슷한 렌더링을 사용하고 있습니다. 잘못된 것입니다. _quantities_field에서는

<%= f.simple_fields_for :quantities do |builder| %> 
<%= render "quantities_fields", :f => builder %> 
<% end %> 

필요하지 않습니다 및 _quantities_fields에

<%= f.input :name, label: "Quantity" %> 

을 조정해야합니다.

UPD 나는 문제가 성분 모델에서 :reject_if -clause에 생각합니다. recipe_params을 대신 : 그것은 강력한 매개 변수에 대한 개인 방법의 관련 이름을 사용하는 것이 좋습니다 컨트롤러에서 1) : 그것은 여기

:reject_if => lambda { |a| a[:amount].blank? } 

BC 당신이 코드 스타일링에없는 성분

를 들어, 수량에 대한 조건을 지정해야 post_params을 작성한 다음 새로운 레시피 작성에 사용하십시오. @recipe = Recipe.new(recipe_params)

2) 두 개의 래서 피가 유사한 것을 사용하는 경우 Recipe, Ingredient와 Quantity 사이의 현재 연관은 Ingredient duplication으로 이어질 것입니다. 그 이유는 단일 연결을 정의하는 belongs_to입니다. 다른 방법을 시도해보십시오 (벨로우즈).

BTW. 최근 비슷한 질문에 답했습니다. 그것을 체크 아웃 : // 로봇 :이 부분

<%= simple_form_for @recipe do |f| %>

에서 누락 How do I reference an existing instance of a model in a nested Rails form?

+0

죄송합니다, 내 잘못, 내 질문에 실수로 _ingredient_fields에서 동일한 코드를 복사, 코드에 썼습니다. 나는 이것을 지금 편집하고 내가 작업해온 실제 코드를 작성했다. 그래서 그게 문제를 일으킨 것이 아닙니다. – user2932226

+0

또한 이전 질문에서 추천 한 바에 따르면 모델 사이에 약간 다른 구조를 사용하여 수량을 통해 제조법과 재료를 연결했습니다. 하지만 그게 내 문제의 원인이라고 생각하지 않습니까? 어떤 도움을 주셔서 감사합니다! – user2932226

+0

Yepp, 문제는 성분이 아닌 모델입니다. – Leger

0

나는 것은 그것이

<%= simple_nested_form_for @recipe do |f| %>

관련 문제