[英]Ruby on Rails: Polymorphic Association Confusion
I am contributing one of the ruby on rails application over GitHub where I faced the following scenario: 我正在GitHub上的ruby on rails应用程序之一中遇到以下情况:
I am having following models which I want to convert to make polymorphic: 我有以下要转换为多态的模型:
class Comment < ActiveRecord::Base
belongs_to :team
belongs_to :user
belongs_to :application
belongs_to :project
end
class Team < ActiveRecord::Base
has_many :comments
end
class Project < ActiveRecord::Base
has_many :comments, -> { order('created_at DESC') }, dependent: :destroy
end
class User < ActiveRecord::Base
end
class Application < Rails::Application
end
I made following changes to make it polymorphic: 我进行了以下更改以使其具有多态性:
Perform database change to removed team_id
, project_id
, application_id
and user_id
and added commentable_id
and commentable_type
to comments
table. 对已删除的team_id
, project_id
, application_id
和user_id
进行数据库更改,并将commentable_id
和commentable_type
添加到comments
表。
Modifications in models as described within rails guides.: 在rails指南中描述的模型修改:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class Team < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Project < ActiveRecord::Base
has_many :comments, as: :commentable, -> { order('created_at DESC') }, dependent: :destroy
end
While I use it with default scope, It doesn't allow me to use with default scope and gives error with below line: 当我将其与默认范围一起使用时,它不允许我与默认范围一起使用,并在以下行中给出错误:
has_many :comments, as: :commentable, -> { order('created_at DESC') }, dependent: :destroy
I am confused to change in following models: 我很困惑要更改以下模型:
class User < ActiveRecord::Base
end
class Application < ActiveRecord::Base
end
Should I need following changes in User
and Application
model? 我需要对User
和Application
模型进行以下更改吗?
class User < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Application < ActiveRecord::Base
has_many :comments, as: :commentable
end
Thanks in Advance! 提前致谢!
if your user/application object needs comments then add 如果您的用户/应用程序对象需要注释,则添加
class User < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Application < ActiveRecord::Base
has_many :comments, as: :commentable
end
else create belongs_to/has_many relationship not polymorphic Eg. 否则创建不是多态的Eg的属属关系。
class User < ActiveRecord::Base
has_many :comments
end
class Application < ActiveRecord::Base
has_many :comments
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.