【问题标题】:Rails polymorphic association and has_many for the same modelRails 多态关联和相同模型的 has_many
【发布时间】:2017-01-06 11:59:02
【问题描述】:

我有属于其他一些模型的评论模型,如 Post、Page 等和 has_one(或 belongs_to?)用户模型。但是我也需要用户可以评论,所以用户必须有很多来自其他用户的评论(这是多态的:可评论关联),他必须有自己的评论,由他编写。 建立这样的协会的最佳方式是什么?如果用户与评论有两种不同的关联,我如何在控制器中为用户阅读和创建评论? 现在我这样做了,我猜这是不对的:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :comments, as: :commentable
  has_many :comments
end

class Comment < ActiveRecord::Base
    belongs_to :commentable, polymorphic: true
    belongs_to :user
end

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :content
      t.references :commentable, polymorphic: true, index: true
      t.belongs_to :user
      t.timestamps null: false
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby polymorphic-associations


    【解决方案1】:

    您需要为该关联使用另一个名称。

    has_many :comments, as: :commentable
    has_many :commented_on, class_name: 'Comment' # you might also need foreign_key: 'from_user_id'.
    

    See has_many's documentation online.

    您的情况不需要foreign_key,但我要指出的是 Just In Case™。默认情况下,Rails 会猜测“{class_lowercase}_id”(所以 user_id 在名为 User 的类中)。

    然后您可以访问这两个关联(class_name 是明确需要的,因为 Rails 无法从 commented_on 找到 Comment)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多