简体   繁体   English

Rails:如何使模型从父模型“继承”属性?

[英]Rails: How to get a model to “inherit” attributes from a parent model?

I have a model "Thing" and a model "Category", which have_many of each other through another model "ThingCategories". 我有一个模型“ Thing”和一个模型“ Category”,它们通过另一个模型“ ThingCategories”彼此之间有很多。 I want each Category to have a certain set of attributes, and when a Thing is created belonging to that Category, I want the Thing to gain those attributes. 我希望每个类别都具有一组特定的属性,并且在创建属于该类别的事物时,我希望事物获得这些属性。 For example, if there's a Category called "film" with the attribute :director, and one called "book" with the attribute :author, and I create a Thing called "Harry Potter" which belongs to both categories, then Harry Potter should have both a :director and :author attribute. 例如,如果有一个名为“电影”的类别,其属性为:导演,而有一个名为“书”的类别,其属性为:作者,而我创建了一个名为“哈利·波特”的事物,则属于这两个类别,那么哈利·波特应该:director和:author属性。 All I want is both attributes listed on the completed things/show view. 我要的都是在完成的事物/显示视图中列出的两个属性。

So far I've created an "Attribute" model and two connecting models "ThingAttribute" and "CategoryAttribute", but I'm not sure where to go from here. 到目前为止,我已经创建了一个“属性”模型和两个连接模型“ ThingAttribute”和“ CategoryAttribute”,但是我不确定从这里开始。 Am I on the right track? 我在正确的轨道上吗?

I'm using rails 4.0.10. 我正在使用Rails 4.0.10。

How I'd do this.. 我该怎么做..

I'd create the attributes as parts of a module. 我将创建属性作为模块的一部分。 So I have a book_helper.rb and movie_helper.rb 所以我有一个book_helper.rb和movie_helper.rb

I'd then import the correct file during the initialise function. 然后,我将在初始化功能期间导入正确的文件。 It would be object specific.. When doing this I'd consider name-spacing the methods so you don't get a clash. 这将是特定于对象的。.在执行此操作时,我将考虑对方法进行命名间隔,以免产生冲突。

I'm not sure if this is the right way, but it would be how I'd go about it (unless someone told me a better way) 我不确定这是否正确,但这将是我的解决方法(除非有人告诉我更好的方法)

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

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