I have a model Client which has many :tours, association in it. I am using this code to provide all the clients with their tours,
render :json => Client.all(:include => :tours)
Now, the requirement has changed such that this object representation loads only tours of a user. Each tour is associated with an user with relation User has many :tours. I tried
render :json => Client.all(:include => :tours, :conditions => ["tours.user_id = ?", params[:user_id]])
This gives me the clients having tours of that user, but lists all the tours of these clients. But, I want only tours of that user only to be listed under each client. Can I do that using :includes?
client.rb
has_many :tours, :dependent => :destroy
user.rb
has_may :tours, :dependent => :destroy
Update
I thought it would be better to add an example to explain my problem. Suppose, there are 3 clients A, B, C.
- Client A has 3 tours (all of user user1)
- Client B has 4 tours (none of user user1)
- Client C has 3 tours (1 of user user1, others of other users)
Now if we use my method to get the response for user1, it will be like this:
[
{
"name": "Client A",
....
"tours": [
{
"name": "Tour1",
....
},
{
"name": "Tour2",
......
},
{
"name": "Tour3",
.....
}
]
},
{
"name": "Client C",
....
"tours": [
{
"name": "Tour4",
...
},
{
"name": "Tour5",
...
},
{
"name": "Tour6",
...
}
]
}
]
You can see that Client B has been omitted, and Client A and Client C has been included, which is correct. But, for Client C, only Tour5 belongs to user user1. But, it has all its tours included. I want my response to omit Tour5 and Tour6, like this:
[
{
"name": "Client A",
....
"tours": [
{
"name": "Tour1",
....
},
{
"name": "Tour2",
......
},
{
"name": "Tour3",
.....
}
]
},
{
"name": "Client C",
....
"tours": [
{
"name": "Tour4",
...
}
]
}
]
I’m only guessing but have you tried something along the lines of: