【问题标题】:How do I add a new attribute to each ActiveRecord in array based on value from another array?如何根据来自另一个数组的值向数组中的每个 ActiveRecord 添加新属性?
【发布时间】:2016-03-02 04:42:55
【问题描述】:

在帮助方面,您始终是不可替代的。我遇到了一个新问题。

我有两个模型。

User(id: integer)
Follower(id: integer, source_user_id: integer, target_user_id: integer)

我通过 get 输入了params[:user_id]

我需要创建一个包含is_following => true/false 的记录数组。

当存在source_user_id = params[:user_id] 的关注者记录时,is_following 应该为真

is_following 在该参数没有关注者记录时应为 false

最有效的方法是什么?

谢谢!

【问题讨论】:

  • 你能显示一些示例数据吗,问题不是很清楚
  • 我正在寻找一个用户列表,它指定具有 params[:user_id] 的特定用户是否关注每个用户。

标签: ruby-on-rails arrays join activerecord


【解决方案1】:

User 模型中添加方法的快速答案:

class User < ActiveRecord::Base
   has_many :followers, foreign_key: :source_user_id

   def is_following? follower_id
     follower_ids.include? follower_id.to_i
   end
end

然后:

user.is_following? params[:user_id]

该关联是根据您的问题假设的。 请注意,这是对您问题的简短回答。您可能想要重新设计关联,将方法移至 Decorator(取决于您的用例)并可能优化查询。

【讨论】:

  • 谢谢,但只有部分代码是正确的。
  • 首先,答案更多是为了给你一个想法,因为你的问题没有包含真正的代码 sn-p 为基础。请使用有效的代码 sn-ps 重新表述您的问题,以供参考。
  • 感谢您的帮助!然而,给你功劳对其他用户是不公平的。他也给了一点。
【解决方案2】:

已编辑以反映您想要的说明。

User 模型中定义一个辅助函数,称为is_following:

def is_following?
  !Follower.where(source_user_id: self.id).empty?
end

现在,您可以使用 map 方法创建一个数组。你必须有一个哈希数组,因为用户没有任何属性来存储布尔值:

User.all.map { |user| {user: user, is_following: user.is_following? } }

【讨论】:

  • 我不是在寻找关注者列表。我正在寻找一个用户列表,该列表指定特定用户是否关注每个用户。
  • 所以使用第二种方案
  • 我不明白它的作用。我需要一个用户对象列表,第二个创建一个跟随者对象列表。
  • 抱歉,我认为你想要的不是很清楚。您是否需要一些用户,并带有一个属性来说明他们是否被关注?
  • 是的,后面是在 params[:user_id] 处给出的用户。
【解决方案3】:

用户模型修改

has_many :followers, class_name: 'Follower', foreign_key: :target_user_id

def is_followed? follower_id
    followers.where(:source_user_id => follower_id).exists?
end

和 API

users = users.map {|user| { user: user, is_following: user.is_followed?(params[:user_id]) } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多