3

누군가가 여기에서 수정을 제안 할 수 있음을 알립니다. 나는 Rails를 처음 접했고 Rails 4.0의 변화를 탐구했다. Rails 4.0에서 간단한 레서피 북 앱을 만들었습니다. 나는 요리법 (name, cook_time, oven_temp, instructions 등)을위한 주요 모델을 가지고있다. 일부 조리법에는 5 가지 성분이 있고 다른 성분에는 20 가지 성분이있을 수 있으므로 has_many 연관성을 지닌 별도의 모델에서 성분을 제거하고 싶습니다. 따라서 조리법에는 has_many Ingredients와 accepts_nested_attributes_for가 있습니다. 재료. 여기 모델은 다음과 같습니다Rails 4.0 & Cocoon : fields_for에 중첩 된 필드가 편집에 나타나지 않습니다.

recipe.rb

class Recipe < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :category 
    has_many :ingredients, :dependent => :destroy 

    validates :name, presence: true, length: { maximum: 50 } 

    accepts_nested_attributes_for :ingredients, 
       :reject_if => lambda { |a| a[:name].blank? }, 
          :allow_destroy => true 
end 

알림

class Ingredient < ActiveRecord::Base 
    belongs_to :recipe 
end 

ingredient.rb은 : 4.0가 더 이상 attr_accessible 사용 레일,하지만 강력한와 컨트롤러에 할당 이동 params.

recipes_controller.rb

class RecipesController < ApplicationController 
    before_action :find_recipe, only: [:show, :edit, :update, :destroy] 
    before_action :set_current_user, except: [:index, :show] 
    respond_to :html, :js 

    ... 

    def edit 
    end 

    def update 
    if @recipe.update_attributes(recipe_params) 
     redirect_to @recipe 
    else 
     render :edit 
    end 
    end 

... 

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

private 

    def recipe_params 
    params.require(:recipe).permit(:id, :name, :category_id, :cook_time, :oven_temp, :calories, :instructions, :notes, :email, ingredients_attributes: [:id, :name]) 
    end 

end 

나는 동적으로 중첩 양식 필드를 관리 할 수 ​​nathanvda에서 우수한 코쿤 보석을 사용하고, 그것은 좋은 작품에서 '조리법 # 새로운'하고 정확하게 정보를 저장합니다. 그러나 성분 필드는 'recipes # edit'보기에 나타나지 않습니다! 여기 내 'form'및 ingredients_fields 부분에 대한 코드가 있습니다. 내가 말했듯이, 아주 간단 모든 오류 검사 및 메시징을 제거

<div class="nested-fields"> 
    <div class="form-group"> 
    <%= f.label :name, "Ingredient", class: "col-lg-2 control-label" %> 
    <div class="col-lg-5"> 
     <%= f.text_field :name, class: "form-control" %> 
    </div> 
    <%= link_to_remove_association "remove", f %> 
    </div> 
</div> 

(약칭 함)

_form.html.erb

<%= form_for @recipe, html: { class: 'form-horizontal' } do |f| %> 

    <fieldset> 
    <legend>Main Information</legend> 

    <div class="field form-group"> 
     <%= f.label :name, "Recipe name", class: "col-lg-2 control-label" %> 
     <div class="col-lg-5"> 
     <%= f.text_field :name, class: "form-control" %> 
     </div> 
    </div> 

    <div class="field form-group"> 
     <%= f.label :cook_time, class: "col-lg-2 control-label" %> 
     <div class="col-lg-5"> 
     <%= f.text_field :cook_time, class: "form-control" %> 
     </div> 
    </div> 
... 
    </fieldset> 

    <legend>Ingredients</legend> 
    <p>Number of ingredients: <%= f.object.ingredients.count unless f.object.ingredients.nil? %></p> 
    <fieldset id="ingredients"> 
    <% f.fields_for :ingredients do |builder| %> 
     <%= render 'ingredient_fields', :f => builder %> 
    <% end %> 
    <p class="links"> 
     <%= link_to_add_association 'add ingredient', f, :ingredients, { class:"btn btn-primary" } %> 
    </p> 
    </fieldset> 

    <fieldset> 
    <legend>How to make it</legend> 
    <div class="field form-group"> 
    <%= f.label :instructions, class: "col-lg-2 control-label" %> 
     <div class="col-lg-5"> 
     <%= f.text_area :instructions, class: "form-control", rows: "7" %> 
     </div> 
    </div> 
... 
    </div> 
    </fieldset> 
<% end %> 

_ingredients_fields.html.erb, 단지 기본 사항. 제가 누락 된 것에 대한 아이디어가 있습니까? 나는 쇼보기에서 편집을로드 할 때 조리법에 재료가 있다는 것을 알고 있습니다. 어떤 조언을 주셔서 미리 감사드립니다!

케빈

답변

6

Ack. 그것은 '='기호처럼 간단했습니다 - < % f.fields_for ... %> 1000 번 보았을 것입니다. 그리고 나는 단지 < % =을 (를) 추가하지 못한 것을 알지 못했습니다.

+1

나는 같은 문제에 몇 시간을 보냈다. 당신이 그것을 알아 낸 것을 기쁘게 생각합니다! –

0
<%= f.fields_for :ingredients do |builder| %> 
+1

스택 오버플로에 오신 것을 환영합니다! 이 코드 스 니펫이 질문을 해결할 수 있지만 [설명 포함] (// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 정말 게시물의 품질을 향상시키는 데 도움이됩니다. 앞으로 독자의 질문에 답하고 있으며 코드 제안의 이유를 알지 못할 수도 있습니다. 또한 주석을 설명하기 위해 코드를 군중시키지 마십시오. 그러면 코드와 설명 모두 가독성이 떨어집니다! –