2012-06-15 106 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