user1608920
user1608920

Reputation: 157

Ruby on Rails. Searching ActiveRecord objects where condition is the presence of one of the associations

I have a Rails code that queries database for employee objects, which have many social_url_for_service (for various services). The way it is implemented, it first gets all employees from database, and then serches for ones with Twitter. Is there any way to look for this association directly (with Employee.find() metod for example) ?

@e = Employee.all
@employees = []
@tweets = []
@e.each do |employee|
  if employee.social_url_for_service(:twitter)
    @employees << employee
    @tweets.concat(Twitter.user_timeline(employee.social_url_for_service(:twitter).split('/').last, count: 3))
  end
end

Upvotes: 0

Views: 439

Answers (1)

Zach Kemp
Zach Kemp

Reputation: 11904

Assuming social_url_for_service is a method that grabs a social_service_link association with a service_name field:

Employee.joins(:social_service_links).where('social_service_links.service_name = ?', "Twitter")

You'll need to update this for your exact table and field names. You can also drop the .where call to return all employees with a service of any kind.

Upvotes: 1

Related Questions