gpt4 book ai didi

ruby-on-rails - 同一模型的 Rails 多态关联和 has_many

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:28 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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 在您的情况下应该不需要,但我指出它是为了以防万一™。默认情况下,Rails 会猜测“{class_lowercase}_id”(所以 user_id 在名为 User 的类中)。

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

关于ruby-on-rails - 同一模型的 Rails 多态关联和 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com