Ruby on Rails:多态关联混淆

时间:2016-03-31 03:34:40

标签: ruby-on-rails ruby ruby-on-rails-3 associations model-associations

我在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_idproject_idapplication_iduser_id,并将commentable_idcommentable_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

我是否需要在UserApplication型号中进行以下更改?

class User < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Application < ActiveRecord::Base
  has_many :comments, as: :commentable
end

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果您的用户/应用程序对象需要注释,则添加

class User < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Application < ActiveRecord::Base
  has_many :comments, as: :commentable
end

否则创建belongs_to / has_many关系不是多态的 例如

class User < ActiveRecord::Base
  has_many :comments
end

class Application < ActiveRecord::Base
  has_many :comments
end
相关问题