has_one | nested attributes -
-
20-09-2019 - |
Question
How would I show one of many nested objects in the index view
class Album < ActiveRecord::Base
has_many: photos
accepts_nested_attributes_for :photos,
:reject_if => proc { |a| a.all? { |k, v| v.blank?} }
has_one: cover
accepts_nested_attributes_for :cover
end
class Album Controller < ApplicationController
layout "mini"
def index
@albums = Album.find(:all,
:include => [:cover,]).reverse
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @albums }
end
end
This is what I have so fare. I just want to show a cover for each album.
Any info on this would be a massive help!!
Solution
In your view iterate over the nested data. i.e.
<% @albums.each do |album| %>
<%= album.name %>
<% # display other album details %>
<%= image_tag album.cover.name %>
<% album.photos.each do |photo| %>
<%= image_tag photo.name %>
<% end %>
<% end %>
In your controller include the photos
in the query results.
@albums = Album.all :include => [:photos]
You don't need to include the :cover
in the query as it is a has_one
association(unless you are using the fields from :cover
in your WHERE
condition).
I suspect you are making the reverse
call to sort the result-set. Use the :order
clause instead.
@albums = Album.all :include => [:photos], :order => "created_at ASC"
OR
@albums = Album.all :include => [:photos], :order => "name ASC"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow