ruby-on-rails – 合并具有相同模型的两个has_many关联的结果

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 合并具有相同模型的两个has_many关联的结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有用户.用户可以戳戳其他用户,也可以自己动手.每个戳都是方向性的,并且不存在组戳.我想列出给定用户的所有戳(传入或传出),而不重复自助(作为incoming_和outgoing_pokes存在).

这是我的模特:

class User < ActiveRecord::Base
  has_many :outgoing_pokes,:class_name => "Poke",:foreign_key => :poker_id
  has_many :incoming_pokes,:foreign_key => :pokee_id
end

class Poke < ActiveRecord::Base
  belongs_to :poker,:class_name => "User"
  belongs_to :pokee,:class_name => "User"
end

我尝试在User模型中创建一个方法来合并戳:

def all_pokes
  outgoing_pokes.merge(incoming_pokes)
end

但是它只返回自我戳(那些既是incoming_px也是outgoing_pokes).想法?是否有一种干净的方法直接使用关联?

此外,在合并列表中,每个poke都有两个布尔值可以记录它们与当前用户的关系.传出和传入的东西.

解决方法

你的all_pokes方法只返回self-pokes的原因是因为outgoing_pokes还不是一个数组,而是你可以链接的AR关系.在这种情况下,merge在执行之前组合查询.

您想要的是实际执行查询并合并结果集:

def all_pokes
  (outgoing_pokes.all + incoming_pokes.all).uniq
end

…或者您可以编写自己的查询

def all_pokes
  Poke.where('poker_id = ? OR pokee_id = ?',id,id)
end

确定它是传入还是传出:

# in poke.rb
def relation_to_user(user)
  if poker_id == user.id
    poker_id == pokee_id ? :self : :poker
  elsif pokee_id == user.id
    :pokee
  else
    :none
  end
end
原文链接:https://www.f2er.com/ruby/270786.html

猜你在找的Ruby相关文章