避免从 Rails 中给定模型的子类创建重复对象
我有一个模型 group.rb
,其子类 organization.rb
、company.rb
等。我想知道是否有办法创建一个名为“Rails Beginners Society”的组织,而不同时创建一个名为“Rails Beginners Society”的公司?就目前情况而言,如果我执行类似 Organization.find_or_create_by_name(:name => @profile.organization)
的操作,我最终不仅会创建一个组织,还会创建一个公司和所有group.rb
的其他子类,其名称是我在控制器中提供的。
任何想法/指导将不胜感激!
我的模型看起来像这样:
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
class Organization < Group
end
等等......
I have a model group.rb
with subclasses organization.rb
, company.rb
, etc. I'm wondering if there is a way to create an organization with the name "Rails Beginners Society" without also creating a company with the name "Rails Beginners Society"? As it stands right now it looks like if I do something like Organization.find_or_create_by_name(:name => @profile.organization)
I end up not only creating an organization, but also a company and all the other subclasses of group.rb
with the name I supply in my Controller.
Any ideas/guidance would be much appreciated!
My Models look like this:
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
class Organization < Group
end
Etc...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您想要做的是STI(单表继承)。 Rails 确实支持这一点。
等等...
如果您的
groups
表中有一个type
列,Rails 应该为您处理所有事情。It sounds like what you're trying to do is STI (Single Table Inheritance). Rails does support this.
etc...
If you have a column
type
in yourgroups
table, Rails should handle everything for you.