【问题标题】:Rails, accepts_nested_attributes_for has_many: through with buildRails,接受_nested_attributes_for has_many:通过与构建
【发布时间】:2013-12-20 12:17:39
【问题描述】:

我知道这里有很多类似的问题,但都没有帮助我。

我有 3 个模型:

class Product < ActiveRecord::Base
   has_many :product_option_types
   has_many :option_types, through: :product_option_types
end

class OptionType < ActiveRecord::Base
    has_many :product_option_types
    has_many :products, through: :product_option_types
end

class ProductOptionType < ActiveRecord::Base
    belongs_to :product
    belongs_to :option_type
end

Table OptionType 预定义如下:

现在在创建新产品时,我还需要使用 product_id 和 option_type id 填充表 product_option_types:这是 product_option_types 表的设计:

据我所知,我需要产品模型中的accepts_nested_attributes_for 来引用product_option_types,所以在产品模型中我需要遵循

accepts_nested_attributes_for :product_option_types, allow_destroy: true

在渲染 new.html.erb 之前,我需要按以下方式构建 product_option_types

@product = Product.new
@product.product_option_types.build(position: 1)

在视图 new.html.erb 中,我使用 collection_select 来显示 option_types:

<%= f.fields_for :product_option_types do |builder| %>
    <%= builder.label :option_type_id, "Options" %>
    <%= builder.collection_select :option_type_id, OptionType.all(order: 'name ASC'), 
                                  :id, :name, { prompt: "Select option..."} %>
<% end %>

最后,在产品控制器的 crate 操作中,我还必须允许关联属性,例如:

permited = params[:product].permit(product_option_types_attributes: [:option_type_id])

所以主要问题是,我是否正确设置了accepts_nested_attributes_for、build、collection_select 和associations?

+:当我使用以下参数建立关联时:

@product.product_option_types.build(position: 1)

然后要传递该信息(位置:1)以创建操作,我必须在表单中使用 hidden_​​field 吗?

【问题讨论】:

  • 对你的第一个问题:嗯,它有效吗?如果不是,会发生什么?对于你的第二个问题,是的,你需要 hidden_field 来传递位置 - 或者如果它不会被修改,你可以简单地设置在你的 create 操作而不是 new
  • 问题真的很大吗?

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


【解决方案1】:

据我了解,您感兴趣的数据是 OptionType。 那么为什么不使用数据而不是关系。

 Product.first.option_types

比关系表更有趣。

从 product_option_types 更改为 option_types。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2011-04-15
    相关资源
    最近更新 更多