0

私は多対多の関係でレシピと材料を持っています。

プレゼンテーションで次のコマンドを定義しました。

<div>
  <%= render :partial => 'ingredients/form',
             :locals => {:form => recipe_form} %>
</div>

部分はで始まります

<%= form_for(@ingredient) do |ingredient_form| %>

しかし@ingredientnillを受け取りました。それから私は試しました

<%= recipe_form.fields_for :ingredients do |builder| %>
    <%= render 'ingredient_fields', f: builder %>
<% end %>

私のレンダリングがあった場所

<p class="fields">
  <%= f.text_field :name %>
  <%= f.hidden_field :_destroy %>
</p>

しかし、何も印刷されませんでした。それから私は試しました

<% @recipe.ingredients.each do |ingredient| %>
    <%= ingredient.name %>
<% end %>

そしてその時だけ、すべての材料が印刷されました。以前の試みで私は何を間違えていましたか?ありがとうございました。

私の材料レシピの関係は次のように定義されています

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

 class Recipe < ActiveRecord::Base
   has_many :ingredient_recipes
   has_many :ingredients, :through => :ingredient_recipes
   ...

   accepts_nested_attributes_for :ingredient_recipes  ,:reject_if  => lambda { |a| a[:content].blank?}


 class IngredientRecipe < ActiveRecord::Base
  attr_accessible :created_at, :ingredient_id, :order, :recipe_id
  belongs_to :recipe
  belongs_to :ingredient
 end
4

1 に答える 1

1

あなたはあなたが何をしようとしているのかを正確に特定していないので、私はあなたが編集して追加できる多くの材料を含むレシピを示すページを持っていると思います。コントローラには、次のようなものがあります。

class RecipeController < ApplicationController
  def edit
    @recipe = Recipe.find(params[:id]
  end
end

また、作成アクションにポストバックするフォームを探していると思います。したがって、次のようなフォームが必要だと思います。

<%= form_for @recipe do |form| %>

  <%= label_for :name %>
  <%= text_field :name %>

  <%= form.fields_for :ingredients do |ingredients_fields| %>
    <div class="ingredient">
      <%= f.text_field :name %>
      <%= f.hidden_field :_destroy %>
    </div>
  <% end %>

<% end %>

また、レシピを変更して、 :ingredientsではなくのネストされた属性を受け入れるようにします。ingredient_recipes

class Recipe < ActiveRecord::Base
   has_many :ingredient_recipes
   has_many :ingredients, :through => :ingredient_recipes
   ...

   accepts_nested_attributes_for :ingredients, :reject_if  => lambda { |a| a[:content].blank?}

そして最後に、コンテンツにattr_accessibleを追加します。

class Ingredient < ActiveRecord::Base
  attr_accessible :content
  ...

それはあなたのために働きますか?

于 2012-06-15T23:02:25.470 に答える