masterial
masterial

Reputation: 2216

How do I add a new attribute to each ActiveRecord in array based on value from another array?

as always you are irreplaceable when it comes to help. I got a new problem.

I have two Models.

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

I have params[:user_id] input via get.

I need to create an array of records that contains is_following => true/false.

is_following should be true when there is a Follower record present for source_user_id = params[:user_id]

is_following should be false when there is no Follower record present for this parameter

What is the most efficient way to do this?

Thank you!

Upvotes: 0

Views: 128

Answers (3)

Christian Rolle
Christian Rolle

Reputation: 1684

The quick answer to add a method in your User model:

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

and then:

user.is_following? params[:user_id]

The association was assumed based on your question. Please note, that this is a short answer to your question. You probably want to redesign your associations, move the method into a Decorator (depending on your use case) and maybe optimize the querying.

Upvotes: 2

masterial
masterial

Reputation: 2216

User Model modification

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

And API

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

Upvotes: -1

Barnaby
Barnaby

Reputation: 127

Edited to reflect the clarification on what you want.

Define a helper function within the User model, called is_following:

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

Now, you can use the map method to create an array. You'll have to have an array of hashes, since users don't have any kind of attribute to store the boolean value:

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

Upvotes: 1

Related Questions