Rails 3 模型在每条记录中只属于不同的表

发布于 2024-11-16 01:00:43 字数 350 浏览 4 评论 0原文

我有一些像这样的模型:

class Alpha < ActiveRecord::Base
 has_many :items 
end    

class Beta < ActiveRecord::Base
 has_many :items
end

class Item < ActiveRecord::Base
 belongs_to :alpha
 belongs_to :beta
end

但我希望每个数据库记录中的项目模型属于 :alpha 或 :beta 但不能同时属于两者。 Rails 3 有什么好的方法吗?或者我应该使用 AlphaItems 和 BetaItems 对其进行建模?

I have some models like these:

class Alpha < ActiveRecord::Base
 has_many :items 
end    

class Beta < ActiveRecord::Base
 has_many :items
end

class Item < ActiveRecord::Base
 belongs_to :alpha
 belongs_to :beta
end

But i want Item model in each database record to belong either to an :alpha or to a :beta but NOT both. Any nice way to do it in Rails 3? or should I model it with AlphaItems and BetaItems instead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮倦 2024-11-23 01:00:43

您可能想为此使用多态关联。更多详细信息 - http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

class Alpha < ActiveRecord::Base
  has_many :items, :as => :itemable
end    

class Beta < ActiveRecord::Base
  has_many :items, :as => :itemable
end

class Item < ActiveRecord::Base
  belongs_to :itemable, :polymorphic => true
end

You probably want to use a Polymorphic Association for this. More details - http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

class Alpha < ActiveRecord::Base
  has_many :items, :as => :itemable
end    

class Beta < ActiveRecord::Base
  has_many :items, :as => :itemable
end

class Item < ActiveRecord::Base
  belongs_to :itemable, :polymorphic => true
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文