Theo Felippe
Theo Felippe

Reputation: 279

Ruby on rails - Retrieve array of ids and using that array to query a different model

I have a model "Events" and each event contains an array of ids for "Genre" (a different model). When I create an event, I check a bunch of boxes and save the checked genres to the database. That is all working fine.

When I run my loop to display all events, the field genre_ids returns me an array with the id's for each selected genre that needs to be retrieved from the genres table.

I tried suggestions that I found but had no success yet.

Genre model:

class Genre < ActiveRecord::Base
  has_and_belongs_to_many :events
end

Event model:

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :genres
end

Events controller:

class EventsController < ApplicationController

  def index
    @event_all = Event.all
  end

 def get_genres(event_id)
   @event_genre = Event.find(event_id).genre_id
 end
 helper_method :get_genres

end

 -------

And finally the loop:

<div id="index-events-wrap">
   <% @event_all.each do |ea| %>
     <div class="item">
     <div class="event-image">
       image here
     </div>
    <ul>
      <li><%= ea.name %></li>
      <li><%= get_genres(ea.id)  %></li>
      <li><%= ea.venue_name %></li>
      <li><%= ea.venue_address %></li>
      <li><%= ea.venue_postcode %></li>
    </ul>
  </div>
<% end %>
</div>

Upvotes: 0

Views: 197

Answers (1)

rewritten
rewritten

Reputation: 16435

Try with:

@event_all = Event.includes(:genres).all

It will make one more query (to avoid multiple instantiation of the Genre instances) and populate all the associations automatically. So in the view you can:

<li><%= ea.genres %></li>

By the way, you should have has_and_belongs_to_many in both classes, otherwise Rails won't understand it.

class Event < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :genres # <- this one
end

If needed, add a migration for the join table, see Do I need to manually create a migration for a HABTM join table?

Upvotes: 3

Related Questions