Ruby on rails 同一模型上有多个多态关联,如何访问正确的行?

Ruby on rails 同一模型上有多个多态关联,如何访问正确的行?,ruby-on-rails,polymorphic-associations,ruby-on-rails-4.1,Ruby On Rails,Polymorphic Associations,Ruby On Rails 4.1,我有一个模型,Post,它有一个Post和一个Received(即发送者和接收者)。发布和接收的用户可以是用户,也可以是组 所以 这可能吗?这对我来说似乎是有意义的,我写一篇帖子也没有问题,但我似乎无法访问帖子来显示 我想我可以使用:(但阅读更多关于多态关联的文章……我想我还没有完全理解) 谢谢您可以这样做,您只需区分多个关联名称: User.rb has_many :posted_posts, class_name: 'Post', as: :posted has_many :rece

我有一个模型,Post,它有一个Post和一个Received(即发送者和接收者)。发布和接收的用户可以是用户,也可以是

所以

这可能吗?这对我来说似乎是有意义的,我写一篇帖子也没有问题,但我似乎无法访问帖子来显示

我想我可以使用:(但阅读更多关于多态关联的文章……我想我还没有完全理解)


谢谢

您可以这样做,您只需区分多个关联名称:

User.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Group.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Post.rb
  belongs_to :posted, polymorphic: true
  belongs_to :received, polymorphic: true
因此,要使用它们:

@user.posted_posts do |post|

end

@user.received_posts do |post|

end

您可以随意命名关联,但请记住,一个模型上不能有多个同名关联。

这看起来是答案,谢谢!为了确认,我是否应该在模型或控制器中添加其他内容,或者让rails框架处理其余内容?我问,因为我已经采取了这些步骤,但仍然无法在日志中找到Post表的任何请求。
User.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Group.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Post.rb
  belongs_to :posted, polymorphic: true
  belongs_to :received, polymorphic: true
@user.posted_posts do |post|

end

@user.received_posts do |post|

end