Vijay
Vijay

Reputation: 453

Active Record Where Clause For Relation In Model

I have two Models User and Site. The User has category like 'basic and premium'. The user has relation to sites one -> many (i.e one user can have more than one sites). Now i want to select sites of premium user. Can someone tell me how to use where clause in ActiveRecord to achieve this?

Upvotes: 2

Views: 355

Answers (3)

Pavan
Pavan

Reputation: 33542

I want to select sites of premium user

This will do

User.includes(:sites).where('users.category = ?', 'premium')

Update

If sites also have categories like 'wordpress or joomla', how do i apply where clause to select only wordpress sites of premium users

For that you need to tweak the query like this

User.includes(:sites).where('users.category = ? and sites.category = ?', 'premium','wordpress')

Upvotes: 2

webster
webster

Reputation: 4012

You can try this also:

@user_ids = User.where(category: 'premium').pluck(:id)
@sites = Site.where(user_id: @user_ids)

Upvotes: 0

Arslan Ali
Arslan Ali

Reputation: 17802

As you said that category is a column, so Rails automatically generates the following method for you:

User.find_by_category("basic")

If you do not want to use this, you can use where method, in which you have to send a key-value pair like following:

User.where(:category => "basic")

And when you have found a user with the category you desired, you can simply call sites on it to get all the associated sites with a particular user.

Upvotes: 0

Related Questions