Darkmatter5
Darkmatter5

Reputation: 1249

Rails - List separated by commas through a join table

I have three tables, one of which is a join table between the other two tables.

  1. Jobs: id
  2. Counties: id
  3. Countyizations: job_ib, county_id

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.

  1. Jobs: has_many :countyizations & has_many :counties, :through => :countyizations
  2. Counties: has_many :countyizations & has_many :jobs, :through => :countyizations
  3. Countyizations: belongs_to :county & belongs_to :job

Upvotes: 1

Views: 361

Answers (2)

lalameat
lalameat

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

vee
vee

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

Related Questions