如何使用
polymorphic associations
?
尝试使用:
class Flag < ActiveRecord::Base
belongs_to :flaggable, polymorphic: true
end
class Topic < ActiveRecord::Base
has_many :flags, as: :flaggable
end
class Post < ActiveRecord::Base
has_many :flags, as: :flaggable
end
class Review < ActiveRecord::Base
has_many :flags, as: :flaggable
end
class UpdateAssociationsOnFlags < ActiveRecord::Migration
def change
remove_index :flags, :topic_id
remove_column :flags, :topic_id
remove_index :flags, :post_id
remove_column :flags, :post_id
remove_index :flags, :review_id
remove_column :flags, :review_id
add_column :flags, :flaggable_id, :integer
add_column :flags, :flaggable_type, :string
add_index :flags, :flaggable_id
end
end
编辑,回复问题作者的评论:
您可以添加不同的关联:
class Flag < ActiveRecord::Base
belongs_to :flaggable, polymorphic: true
belongs_to :reporter, class_name: 'User', foreign_key: :reporter_id
end
class User < ActiveRecord::Base
has_many :reported_flags, class_name: 'Flag', foreign_key: :reporter_id
end
class AddUserForeignKeyToFlags < ActiveRecord::Migration
def change
add_column :flags, :reporter_id, :integer
add_index :flags, :reporter_id
end
end