Reputation: 138
In my rails app, I have a filter which shows all the jobs based on parameters passed into my scopes which all works fine, but as an extension to that, I have an ajax call that limits the jobs you can pick based on the projects and clients you select in the filter. Here are my relationships:
A client has many projects
A project belongs to a client and has many jobs
A Job belongs to a project
I can list all the projects based on the client and all the jobs based on a project, but what I am having trouble with is listing all the jobs when just a client is specified, so, getting all the projects for that client and then getting all the jobs for all those projects.
I'm guessing I have to use a join to get this to work, but have tried for a couple of days with no luck :(
If anyone could point me in the direction of a good resource I can look over to try solve this problem it would be greatly appreciated
Upvotes: 1
Views: 125
Reputation: 138
Before this feature worked models looked as follows -
class Client < ActiveRecord::Base
has_many :projects
end
class Project < ActiveRecord::Base
belongs_to :client
has_many :jobs
end
class Job < ActiveRecord::Base
belongs_to :project
end
In order to get Jobs based only on a client, a has_many through relationship had to be set up in the client model.
class Client < ActiveRecord::Base
has_many :projects
has-many :jobs, :through => :projects
end
Then in your controller, you can get all the jobs through the client id by using this new relationship -
@jobs = Client.find(params[:id]).jobs
which will return all the jobs for the client that it finds. Once again thanks to sarnold for the link to the guide that got me to this solution
Upvotes: 1