I have a model that has the following association:
class Tournament < ActiveRecord::Base
has_one :gallery, dependent: :destroy
has_many :gallery_images, :through => :gallery, dependent: :destroy
end
I would like to paginate just the gallery_images as opposed to the tournament itself but as I am getting the gallery_images as a nested attribute I'm not sure how to do this using will_paginate
Controller
def galleries
@tournaments = Tournament.all
#tried this
@gallery_images = @tournaments.gallery_images.paginate(:page => params[:page], :per_page => 9)
end
View
<% @tournaments.each do |t| %>
<div>
<div class="clear"></div>
<ul class="team-gallery">
<% t.gallery_images.each do |g| %>
<li>
<%= link_to image_tag(g.photo.url(:gallery_large)), g.photo.url(:gallery_large), class: 'clb-photo' %>
</li>
<% end %>
</ul>
</div>
How can I paginate just the t.gallery_images?
Are you sure this is working code?
@gallery_images = @tournaments.gallery_images.paginate(:page => params[:page], :per_page => 9)
You are calling gallery_images
, what appears to be an instance method, on an ActiveRecord collection, which is essentially an array. That won't work.
I suspect you want to loop over the tournaments and call paginate on the images of each tournament.
<% @tournaments.each do |t| %>
<%= will_paginate t.gallery_images.paginate(page: params[:page], per_page: 9) %>
<% end %>
You can create an instance method on the Tournament
model to save you from writing all that each time you want to paginate tournament images.
class Tournament
def paginated_images(page, per_page = 9)
gallery_images.paginate(page: page, per_page: per_page)
end
end
Then you can do this in your view:
<% @tournaments.each do |t| %>
<% images = t.paginated_images(params[:page]) %>
<% images.each do |image| %>
<%= image_tag image %>
<% end %>
<%= will_paginate images %>
<% end %>