我在GitHub上贡献了一个ruby on rails应用程序,在那里我遇到了以下场景:
我有以下模型,我想转换成多态的:
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我做了以下更改,使其具有多态特性:
执行数据库更改以删除team_id、project_id、application_id和user_id,并将commentable_id和commentable_type添加到comments表中。
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虽然我将它与默认作用域一起使用,但它不允许我与默认作用域一起使用,并给出了以下行的错误:
has_many :comments, as: :commentable, -> { order('created_at DESC') }, dependent: :destroy我对以下模型的更改感到困惑:
class User < ActiveRecord::Base
end
class Application < ActiveRecord::Base
end我是否需要在User和Application模型中进行以下更改?
class User < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Application < ActiveRecord::Base
has_many :comments, as: :commentable
end提前感谢!
发布于 2016-03-31 12:25:12
如果您的用户/应用程序对象需要注释,则添加
class User < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Application < ActiveRecord::Base
has_many :comments, as: :commentable
end否则create belongs_to/has_many关系不是多态的,例如。
class User < ActiveRecord::Base
has_many :comments
end
class Application < ActiveRecord::Base
has_many :comments
endhttps://stackoverflow.com/questions/36323664
复制相似问题