Reputation: 1249
I have three tables, one of which is a join table between the other two tables.
I want to create a list of counties a specific job has associations with. I'm trying to use something like:
<%= @counties.map { |county| county.id }.join(", ") %>
But this obviously is not using the countyizations table. How can I change the above code to accomplish what I need? Also, I'd like to list the counties alphabetically in ASC
order.
P.S.
I suppose I should have added how I'm linking my tables in my models.
Upvotes: 1
Views: 361
Reputation: 754
I am not sure if I understand you correctly. Is the following what you want?
class Job < ActiveRecord::Base
has_many :countries, :through => :countyizations
end
class County < ActiveRecord::Base
has_many :jobs, :through => :countyizations
end
<%= @job.counties.sort{|a, b| a.name <=> b.name}.map{ |county| county.name }.join(", ") %>
I think use "has_many_and_belongs_to" instead "of has_many" may work also.
Upvotes: 1
Reputation: 38645
For a given job.id
you can use this this return all the counties
filtered by the given job.
<%= @counties.order('name asc').includes(:jobs).where('jobs.id = ?', job.id) %>
Replace job.id
based on your requirement, you could set a @job
instance variable in the controller and use in the view instead.
Or even better move this code to controller action:
# controller
def show
job_name = ...
@counties = ...
@county_jobs = @counties.order('name asc').includes(:jobs).where(jobs.name = ?', job_name)
end
Then in your view, to show all the counties that have the searched job:
<%= @counties.map(&:id).join.(',') %>
Upvotes: 1