加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:22:03 所属栏目:百科 来源:网络整理
导读:我有用户.用户可以戳戳其他用户,也可以自己动手.每个戳都是方向性的,并且不存在组戳.我想列出给定用户的所有戳(传入或传出),而不重复自助(作为incoming_和outgoing_pokes存在). 这是我的模特: class User ActiveRecord::Base has_many :outgoing_pokes,:cla
我有用户.用户可以戳戳其他用户,也可以自己动手.每个戳都是方向性的,并且不存在组戳.我想列出给定用户的所有戳(传入或传出),而不重复自助(作为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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读