包含其他模型的模型

时间:2015-06-19 00:20:59

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

我的术语有点偏,但我会尽量解释这个。

我目前正在开发一种具有不同类型产品的应用程序:西装,鞋子,衬衫。这些都是没有类似继承点的独立模型。拥有Collection的用户应该能够将其中一个或多个添加到Collection中。

我正在考虑使用has_many:through,但这似乎并不优雅。我必须为每个模型创建3个类似的连接表(或者我认为)。有更好的解决方案吗?如果解决方案需要我按原样修改结构,那么我现在可以使用另一种解决方案吗?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

如果用户拥有一个系列,那么套装,鞋子和衬衫必须属于用户。此外,您还需要使用嵌套属性。所以,你会有类似的东西:

<强> user.rb

has_many :suits
has_many :shoes
has_many :shirts
accepts_nested_attributes_for :suits
accepts_nested_attributes_for :shoes
accepts_nested_attributes_for :shirts

<强>球衣

belongs_to :user

而且,您可以使用此表单代码添加产品:

form_for @user do |f|
 f.fields_for :shoes, @user.shoes.new do |builder|
  builder.text_field :price
  ...
 end
 f.fields_for :suits, @user.suits.new do |builder|
  builder.text_field :price
  ...
 end
end
相关问题