【问题标题】:How to build children of a nested form in the controller如何在控制器中构建嵌套表单的子级
【发布时间】:2011-07-16 20:52:48
【问题描述】:

我知道如何在控制器中构建第二个对象,但是如何构建第三个或第四个?

在我的情况下,我需要构建 3。

Location - has_many :product_dates, :products
ProductDate - has_many :products & belongs_to :location
Product - belongs_to :location, :product_date

我很容易建立位置和产品日期:

def new
  @location = Location.new
  @location.product_dates.build
end

现在我需要在表单上构建产品。谁能告诉我如何做到这一点?

编辑:完整答案:

def new
    @location = Location.new
    product_date = @location.product_dates.build
    product_date.products.build
end

    <%= form_for @location do |f| %>
    <%= f.text_field :business %>
    <%= f.text_field :address %>

    <%= f.fields_for :product_dates do |date| %>
    <%= date.date_select :date %>

    <%= date.fields_for :products do |product| %>
    <%= product.text_field :name %>
     <%= product.text_field :price %>
    <%= product.text_field :tag_list %>
    <% end %>
    <% end %>
    <%= f.submit "Create" %>        
<% end %>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 nested nested-forms


    【解决方案1】:

    你会学到一切in video here

    编辑:

    更改嵌套部分:

    <%= f.fields_for :product_dates do |date| %>
      <%= date.date_select :date %>
      <%= date.fields_for :products do |product| %>
       <%= product.text_field :name %>
       <%= product.text_field :price %>
       <%= product.text_field :tag_list %>
      <% end %>
    <% end %>
    

    因为products 嵌套在product_dates

    【讨论】:

    • 但是它使用了“倍”的能力,我不需要,我只需要一个实例。
    • 然后不要循环,删除times :)
    • 你怎么不循环?我不明白什么是循环。
    • 3.times {} 是一个循环:大括号之间的代码将被执行 3 次。所以如果你删除它,它只会被执行一次。
    • OK 在控制台中它确实有效,但我在表单上看不到它。查看我的编辑。
    【解决方案2】:

    添加到您的控制器:

    def new
      @location = Location.new
      @product_dates = @location.product_dates.build
      @product = @product_dates.product.build
    end
    

    在你的 ProductDate 模型中:

    class ProductDate < ActiveRecord::Base
      accepts_nested_attributes_for :products
    ...
    

    在你的位置模型中:

    class Location < ActiveRecord::Base
      accepts_nested_attributes_for :product_dates
    ...
    

    你的表格应该是这样的:

    <% f.fields_for :product_dates do |date| %>
      <%= date.text_field :content %>
      <% date.fields_for :products do |product| %>
        <%= product.text_field :content %>
      <%end %>
    <% end %>
    

    【讨论】:

    • 对于现在想要显示现有日期的任何人,您可以添加一个 if 语句来测试它是否是新记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多