识别 Rails 中两个模型之间多个一对一关系的关系
我有以下两个模型:
class Project < ActiveRecord::Base
has_one :start_date, :class_name => 'KeyDate', :dependent => :destroy
has_one :end_date, :class_name => 'KeyDate', :dependent => :destroy
并且
class KeyDate < ActiveRecord::Base
belongs_to :project
给定数据库中与项目相关的某个关键日期:
@key_date = KeyDate.find(:first)
是否有一种方法可以内省关系以检查 @key_date 是否与项目相关(作为 start_date 或 end_date)?
I have the following two models:
class Project < ActiveRecord::Base
has_one :start_date, :class_name => 'KeyDate', :dependent => :destroy
has_one :end_date, :class_name => 'KeyDate', :dependent => :destroy
and
class KeyDate < ActiveRecord::Base
belongs_to :project
Given a certain key date from the database related to a project:
@key_date = KeyDate.find(:first)
is there a way to introspect the relationship to check if the @key_date is related to the project as start_date or as end_date?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个很好的方法是对
KeyDate
类使用单表继承,这可以让你做到
A nice way would be to use single table inheritance for the
KeyDate
classthis lets you do
一种干净的方法是创建 STI:
http://api.rubyonrails .org/classes/ActiveRecord/Base.html
请参阅我在此处提供的一个示例:
Rails 设计在有 STI 时向注册表添加字段
One clean way to do what you want is to create STI:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html
See one example I gave here:
Rails devise add fields to registration form when having STI
只是大声思考......
说实话,我不明白你为什么需要这个。无论如何,你肯定总是能掌控一个项目吗?
Just thinking aloud...
To be honest I can't see why you'd ever need this. Surely you're always going to have a handle on a project anyway?