Cheers! I am trying to get the municipalities of an association in a collection, however I am having difficulties, the municipalities are an association between companies and municipalities, therefore, I would like the collection to print the municipalities associated with the companies that publish those jobs, to To make it simpler, place the current association:
Municipality.rb
has_many :enterprises
Enterprise.rb
belongs_to :muncipality
has_many :jobs
Job.rb
belongs_to :enterprise
If job was directly associated with Municipality I could easily get it like this, using a scope, however I want to take advantage of the companies, my code here:
job.rb
scope :municipality, -> (municipality_id) { where(municipality_id: municipality_id) }
jobs_controller.rb
def index
if params[:municipality_id].present?
@jobs = Job.municipality(params[:municipality_id]).paginate(:page => params[:page], :per_page => 9)
else
@jobs = Job.all.paginate(:page => params[:page], :per_page => 9)
end
end
index.html.erb
<%= form_tag({ controller: :jobs, action: :index }, { method: :get }) do %>
<div class="input-group no-margin">
<%= select_tag(:municipality_id, options_from_collection_for_select(Municipality.all, :id, :name), { :include_blank => "Todos los municipios", class: "input-group-field" }) %>
<div class="input-group-button">
<%= button_tag( :class => "button secondary", name: nil ) do %>
<i class="fa fa-search" aria-hidden="true"></i>
<% end %>
</div>
</div>
<% end %>
The fact that there is no direct association between
Job
andMunicipality
does not imply that it cannot be usedmunicipality_id
with the modelJob
, you simply have to do a JOIN with the modelEnterprise
, which will give you access to the municipality throughenterprises.municipality_id
.Considering the above, the
scope
enJob
would look like this:Of course, since you're building the
where
, you could omit the table nameenterprises
, since the columnmunicipality_id
is only found in that table; for instance:It is important to note that you cannot use something like
since ActiveRecord will automatically add the table
jobs
tomunicipality_id
(iejobs.municipality.id
) and the query will return an error.