[英]Rails 4: can a child model belong_to two different parent models
In my initial Rails 4 app, I had the following models: 在我最初的Rails 4应用程序中,我具有以下模型:
User
has_many :administrations
has_many :calendars, through: :administrations
has_many :comments
Calendar
has_many :administrations
has_many :users, through: :administrations
has_many :posts
has_many :comments, through: :posts
Administration
belongs_to :user
belongs_to :calendar
Post
belongs_to :calendar
has_many :comments
Comment
belongs_to :post
belongs_to :user
I just added a new Ad
model to the app: 我刚刚在应用中添加了新的Ad
模型:
Ad
belongs_to :calendar
And now I would like to allow users to write comments about the ad records. 现在,我想允许用户撰写有关广告记录的评论。
Can I use my existing Comment
model and do something like: 我可以使用现有的Comment
模型执行以下操作:
Ad
belongs_to :calendar
has_many :comments
Comment
belongs_to :post
belongs_to :user
Or do I need to create a distinct "Comment" model, that I would call for instance AdComments
or Feedback
? 还是我需要创建一个独特的“评论”模型,例如AdComments
或Feedback
?
You need to use polymorphic associations . 您需要使用多态关联 。 Something on the lines of this: 与此类似的东西:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class Ad < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Product < ActiveRecord::Base
has_many :comments, as: :commentable
end
And the migration would look like: 迁移看起来像:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.references :commentable, polymorphic: true, index: true
t.timestamps null: false
end
end
end
I guess you already have the comments table, so you should rather change the table with 我想您已经有了注释表,因此您应该改用
class ChangeComments < ActiveRecord::Migration
def change
change_table :comments do |t|
t.rename :post_id, :commentable_id
t.string :commentable_type, null: false
end
end
end
Also beware, that if you have live data you should update the commentable_type
field of all already existing comments to Post
. 还要注意,如果您拥有实时数据,则应将所有现有注释的commentable_type
字段更新为Post
。 You can either do it in a migration or from the console. 您可以在迁移中或从控制台中进行。
Comment.update_all commentable_type: 'Post'
We don't need to use any new model, you can just refactor the current Comment model with polymorphic 我们不需要使用任何新模型,您只需使用多态来重构当前的Comment模型
So, a comment always belongs to a user, and belongs to a post or ad 因此,评论始终属于用户,并且属于帖子或广告
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.