2012-06-15 105 views
0

我有食譜和成分在多對多的關係。紅寶石在鐵軌上 - 呈現多對多關係

我在演示文稿中定義了以下命令。

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

部分始於

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

但接收@ingredient nill。 然後我試圖

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

我相信@ingredient是零,因爲你的控制器的行爲正在發生。你介意用那個編輯你的文章嗎? – DaMainBoss

+0

謝謝。但它確實顯示了我最後一次嘗試的成分 - @ recipe.ingredients.each。這是否意味着我的成分在那裏?我有控制器配方和ingredienet和他們的模型和IngredientRecipe了。我應該在編輯中添加什麼方法? – Jeb

回答

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 
    ... 

這是否適合您?

+0

非常感謝。你的假設是準確的。我已經寫下了所有的建議,但最後一個。改變has_many:ingredient_recipes:成分做到了一切。順便說一句,我應該離開兩條線has_many:ingredient_recipes && has_many:ingredients,:through =>:ingredient_recipes。就像我原來的問題一樣? – Jeb

+1

很高興工作。是的,你需要配方中的這兩行。 – iHiD