【问题标题】:Ruby on Rails: Polymorphic Association ConfusionRuby on Rails:多态关联混淆
【发布时间】: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_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

提前致谢!

【问题讨论】:

  • 您的用户/应用程序对象是否需要 cmets。如果是,则添加它
  • 你试过has_many :comments, :through =&gt; :commentable吗?

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


【解决方案1】:

如果您的用户/应用程序对象需要 cmets 然后添加

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多