【问题标题】:Rails 3.1 - Editing Attributes in join models?Rails 3.1 - 在连接模型中编辑属性?
【发布时间】:2012-06-13 16:14:47
【问题描述】:

我很难通过连接模型来编辑 has_many 中的属性。我已经设置了一个非常简单的应用程序来进行实验;食谱、配料和 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 %>

干杯!!

【问题讨论】:

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


    【解决方案1】:

    用 f 在第二个嵌套 fields_for 中替换 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 %>    
    

    【讨论】:

    • 如果只有一种成分,那效果很好,但如果有更多,它似乎会返回额外的结果....如果有两种成分,你会在每一行都列出它们......重复,那么 2x2 是否有意义?
    猜你喜欢
    • 2021-01-18
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多