Ruby on rails 如何实现引用用户的多态关系?

Ruby on rails 如何实现引用用户的多态关系?,ruby-on-rails,ruby,model,polymorphism,Ruby On Rails,Ruby,Model,Polymorphism,首先,我有一个多态关联设置,因为注释可以属于任何对象(在我的文章和文章中) 我想说: u = user.first u.comments #This will list all comments from a user u.comments.where(:commentable_type => "Post") f = Food.first f.comments.first.user #give me the user that posted the first comment 这条

首先,我有一个多态关联设置,因为注释可以属于任何对象(在我的文章和文章中)

我想说:

u = user.first
u.comments #This will list all comments from a user
u.comments.where(:commentable_type => "Post")  
f = Food.first
f.comments.first.user #give me the user that posted the first comment
这条线不行。它生成一个sql: 从“评论”中选择“评论”。*其中“评论”。“可评论的”id“=1和“评论”。“可评论的”类型“=“用户”和“评论”。“可评论的”类型“=“帖子”

显然,这将返回一个空列表,因为注释不能属于两种类型。我还想说:

u = user.first
u.comments #This will list all comments from a user
u.comments.where(:commentable_type => "Post")  
f = Food.first
f.comments.first.user #give me the user that posted the first comment
这是我的基本模型。。。有什么改变的建议吗

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

class Post < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class User < ActiveRecord::Base
    has_many :comments, :as => :commentable
end
class注释true
终止
类Post:可评论
终止
类文章:可评论
终止
类用户:可评论
终止

我认为您应该查看您的评论模型,它应该如下所示:

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

如果您希望尝试这种方法,请不要忘记迁移。

我认为您应该查看您的注释模型,它应该如下所示:

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

如果您希望尝试这种方法,请不要忘记迁移。

您应该能够执行以下操作以实现您的目标:

u.comments.map{| cmt | Post.find(cmt.commentable)}

文章也是如此。这将返回一个post或article数组。如果它们不存在,它将给出一个错误,因此您必须对此进行修改


我不完全理解你的第二个问题。如果f.comments.first只返回一条注释,那么.user应该返回该注释的用户,假设您的类用户和注释设置正确(正如Alexandre Abreu指出的那样,用户有许多注释/注释属于用户),但也许我误解了你的问题。

你应该能够做到以下几点来实现你想要的:

u.comments.map{| cmt | Post.find(cmt.commentable)}

文章也是如此。这将返回一个post或article数组。如果它们不存在,它将给出一个错误,因此您必须对此进行修改


我不完全理解你的第二个问题。如果f.comments.first只返回一条注释,那么.user应该返回该注释的用户,假设您的类用户和注释设置正确(正如Alexandre Abreu指出的那样,用户有许多注释/注释属于用户),但也许我误解了你的问题。

你能不能也发布你的用户模型定义(app/models/User.rb)?你能不能也发布你的用户模型定义(app/models/User.rb)?嗯。。。我从未想过查询注释模型本身。谢谢这可能行得通。别忘了从用户模型中的关联中删除
:as=>:commentable
位。嗯。。。我从未想过查询注释模型本身。谢谢这可能会起作用。不要忘记从用户模型中的关联中删除
:as=>:commentable
位。在多形关联中,u.comments仅返回“User”类型的注释。我确信我的模型都是乱七八糟的,不管怎样:\n在多形关联中,u.comments只返回“User”类型的注释。我确信我的模型都是乱七八糟的:\