Rails 4:子模型可以属于两个不同的父模型吗? [英] Rails 4: can a child model belong_to two different parent models
问题描述
在我最初的Rails 4应用程序中,我具有以下模型:
In my initial Rails 4 app, I had the following models:
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
我刚刚向应用程序添加了新的Ad
模型:
I just added a new Ad
model to the app:
Ad
belongs_to :calendar
现在,我希望允许用户撰写有关广告记录的评论.
And now I would like to allow users to write comments about the ad records.
我可以使用现有的Comment
模型并执行以下操作吗:
Can I use my existing Comment
model and do something like:
Ad
belongs_to :calendar
has_many :comments
Comment
belongs_to :post
belongs_to :user
还是我需要创建一个独特的注释"模型,例如我将其称为AdComments
或Feedback
?
Or do I need to create a distinct "Comment" model, that I would call for instance AdComments
or 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
迁移看起来像:
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
还请注意,如果您拥有实时数据,则应将所有现有注释的commentable_type
字段更新为Post
.您既可以在迁移中也可以从控制台中完成.
Also beware, that if you have live data you should update the commentable_type
field of all already existing comments to Post
. You can either do it in a migration or from the console.
Comment.update_all commentable_type: 'Post'
这篇关于Rails 4:子模型可以属于两个不同的父模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!