【发布时间】:2016-03-31 03:34:39
【问题描述】:
我在 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 表。
模型中的修改如导轨指南中所述。:
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
提前致谢!
【问题讨论】:
-
您的用户/应用程序对象是否需要 cmets。如果是,则添加它
-
你试过
has_many :comments, :through => :commentable吗?
标签: ruby-on-rails ruby ruby-on-rails-3 associations model-associations