一个模型可以属于其他两个模型中的任何一个吗
Can a model belong to either one of two other models
我会尽力解释这一点。
我有3个模型。
分发事件
主要作业
次要作业
我需要 DistributionEvent 到 belong_to PrimaryAssignment 或 SecondaryAssignment 并显示在数据库中的同一列上。
所以像这样
class DistributionEvent < ActiveRecord::Base
belongs_to :primaryassignment
belongs_to :secondaryassignment
end
class PrimaryAssignment < ActiveRecord::Base
has_many :distribution_event
end
class SecondaryAssignment < ActiveRecord::Base
has_many :distribution_event
end
但是 DistributionEvent 在 table 中应该只有一列(作业或其他内容)指向主要作业或次要作业。
我希望这是有道理的。
有人知道如何有效地实现这一点吗?
谢谢!
是的,具有多态关联。可以在此处找到文档:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
class DistributionEvent < ActiveRecord::Base
belongs_to :assignment, polymorphic: true
end
class PrimaryAssignment < ActiveRecord::Base
has_many :distribution_events, as: :assignment
end
class SecondaryAssignment < ActiveRecord::Base
has_many :distribution_events, as: :assignment
end
确保还为以下类型添加一列:
class AddAssignmentTypeToDistributionEvent < ActiveRecord::Migration
def change
add_column :distribution_events, :assignment_type, :string
end
end
我会尽力解释这一点。
我有3个模型。
分发事件 主要作业 次要作业
我需要 DistributionEvent 到 belong_to PrimaryAssignment 或 SecondaryAssignment 并显示在数据库中的同一列上。
所以像这样
class DistributionEvent < ActiveRecord::Base
belongs_to :primaryassignment
belongs_to :secondaryassignment
end
class PrimaryAssignment < ActiveRecord::Base
has_many :distribution_event
end
class SecondaryAssignment < ActiveRecord::Base
has_many :distribution_event
end
但是 DistributionEvent 在 table 中应该只有一列(作业或其他内容)指向主要作业或次要作业。
我希望这是有道理的。
有人知道如何有效地实现这一点吗?
谢谢!
是的,具有多态关联。可以在此处找到文档:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
class DistributionEvent < ActiveRecord::Base
belongs_to :assignment, polymorphic: true
end
class PrimaryAssignment < ActiveRecord::Base
has_many :distribution_events, as: :assignment
end
class SecondaryAssignment < ActiveRecord::Base
has_many :distribution_events, as: :assignment
end
确保还为以下类型添加一列:
class AddAssignmentTypeToDistributionEvent < ActiveRecord::Migration
def change
add_column :distribution_events, :assignment_type, :string
end
end