0

結合モデルを介して has_many の属性を編集することに頭を悩ませています。実験用に非常に単純なアプリをセットアップしました。Recipe、Ingredients、および Recipe_Ingredients (結合)。

誰もがこれをうまく機能させるのを助けることができますか? そのままでは、結合モデルから「数量」を取得しますが、実際の成分は取得しません。

誰でもダウンロードしてプレイできる公開レポジトリを作成しました: https://github.com/EssentialMusic/Recipes

モデル:

class Ingredient < ActiveRecord::Base
  attr_accessible :name  
  has_many :recipe_ingredients, :dependent => :destroy
  has_many :recipes, :through => :recipe_ingredients
end

class Recipe < ActiveRecord::Base
  attr_accessible :author, :description, :name, :recipe_ingredients_attributes, :ingredients_attributes
  has_many :recipe_ingredients, :dependent => :destroy
  has_many :ingredients, :through => :recipe_ingredients
  accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
  accepts_nested_attributes_for :recipe_ingredients
end

class RecipeIngredient < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
  attr_accessible :measure, :qty, :special_instructions
end

フォーム

<%= 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 %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :author %><br />
    <%= f.text_field :author %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>

<div>
    <%= f.fields_for :recipe_ingredients do |ri| %>
    <%= ri.text_field :qty %> - 
        <%= ri.fields_for :ingredients do |i| %>
            <%= i.text_field :name %><br>
        <% end %>   
    <% end %>   
</div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

乾杯!!

4

1 に答える 1

0

次のように、2 番目にネストされた fields_for の ri を f に置き換えます。

<%= f.fields_for :recipe_ingredients do |ri| %>
 <%= ri.text_field :qty %> -
      <%= **f**.fields_for :ingredients do |i| %>
         <%= i.text_field :name %><br>
      <% end %>
<% end %>    
于 2012-06-13T20:58:03.960 に答える