我有以下两种模式:
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?
答案 0 :(得分:1)
一种很好的方法是对KeyDate
类使用单表继承
class KeyDate < ActiveRecord::Base
belongs_to :project
end
class StartDate < KeyDate
end
class EndDate < KeyDate
end
class Project < ActiveRecord::Base
has_one :start_date, :dependent => :destroy
has_one :end_date, :dependent => :destroy
end
class CreateKeyDatesMigration < ActiveRecord::Migration
def up
create_table :key_dates do |t|
t.date :date
t.string :type #this is the magic column that activates single table inheritance
t.references :project
end
end
…
end
这可以让你做到
@key_date = KeyDate.find(:first)
@key_date.type # => "StartDate"
答案 1 :(得分:0)
一种干净的方式来做你想做的就是创建STI:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html
参见我在这里给出的一个例子:
Rails devise add fields to registration form when having STI
答案 2 :(得分:0)
大声思考......
class KeyDate < ActiveRecord::Base
belongs_to :project
def start_date?
project.start_date == self
end
def end_date?
project.start_date == self
end
date_type
[:start_date, :end_date].find {|sym| send("#{sym}?") }
end
end
说实话,我不明白为什么你需要这个。当然,你总是会对项目有所了解吗?