Rails 3.1 - 编辑连接模型中的属性?

时间:2012-06-13 16:14:47

标签: ruby-on-rails ruby-on-rails-3 activerecord

我很难通过连接模型在has_many中编辑属性。我已经设置了一个非常简单的应用程序来进行实验;食谱,配料和食谱_成分(加入)。

任何人都可以帮助完成这项工作吗?事实上,它会从连接模型中提取'数量',而不是实际成分。

我已经公开回购任何人都可以下载玩: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 %>

干杯!!

1 个答案:

答案 0 :(得分:0)

在第二个嵌套的fields_for中用f替换ri,如下所示:

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