简体   繁体   English

包含其他模型的模型

[英]A Model That Contains Other Models

I may have the terminology a bit off, but I'm going to try to explain this as much as possible. 我可能对术语有些不了解,但是我将尽力解释这一点。

I'm currently working on an application that has different types of products: suits, shoes, shirts. 我目前正在开发具有不同类型产品的应用程序:西服,鞋,衬衫。 These are all separate models that don't have a similar point of inheritance. 这些都是独立的模型,没有相似的继承点。 A User, who owns a Collection, should be able to add one or many of these to the Collection. 拥有一个收藏集的用户应该能够将其中一个或多个添加到收藏集中。

I was thinking of using has_many :through, but that does not seem very elegant. 我当时在考虑使用has_many:through,但这似乎并不优雅。 I would have to create 3 similar joining tables for each model (or so I think). 我必须为每个模型创建3个相似的联接表(或者,我认为)。 Is there a better solution? 有更好的解决方案吗? And if the solution requires I modify the structure as is, is there another solution that I could get by with for now? 并且,如果该解决方案要求我按原样修改结构,那么现在是否可以使用另一种解决方案?

Thank you in advance. 先感谢您。

If user own a collection, than suits, shoes and shirts must belong to user. 如果用户拥有一个收藏,则西服,鞋子和衬衫必须属于用户。 Also, you need to use nested attributes. 另外,您需要使用嵌套属性。 So, you'll have something like: 因此,您将获得类似以下内容的信息:

user.rb 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

shirts 衬衫

belongs_to :user

And than, you can use this form code to add products: 而且,您可以使用以下表单代码添加产品:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM