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>
Try with:
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:
By the way, you should have
has_and_belongs_to_manyin both classes, otherwise Rails won’t understand it.If needed, add a migration for the join table, see Do I need to manually create a migration for a HABTM join table?