ruby-on-rails - Rails 中的 will_paginate 嵌套对象

标签 ruby-on-rails ruby will-paginate

我有一个具有以下关联的模型:

class Tournament < ActiveRecord::Base
has_one :gallery, dependent: :destroy
has_many :gallery_images, :through => :gallery, dependent: :destroy
end

我只想对 gallery_images 进行分页,而不是对锦标赛本身进行分页,但是当我将 gallery_images 作为嵌套属性获取时,我不确定如何使用 will_paginate 进行分页

Controller

def galleries
  @tournaments = Tournament.all
  #tried this
  @gallery_images = @tournaments.gallery_images.paginate(:page => params[:page], :per_page => 9)
end

查看

                 <% @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>
                    

我怎样才能只对 t.gallery_images 进行分页?

最佳答案

您确定这是有效代码吗?

@gallery_images = @tournaments.gallery_images.paginate(:page => params[:page], :per_page => 9)

您正在 ActiveRecord 集合上调用 gallery_images,这似乎是一个实例方法,它本质上是一个数组。那是行不通的。

我怀疑您想遍历锦标赛并对每场锦标赛的图像调用分页。

<% @tournaments.each do |t| %>
  <%= will_paginate t.gallery_images.paginate(page: params[:page], per_page: 9) %>
<% end %>

您可以在 Tournament 模型上创建一个实例方法,这样您就不必在每次要对锦标赛图像进行分页时都编写所有这些内容。

class Tournament
  def paginated_images(page, per_page = 9)
    gallery_images.paginate(page: page, per_page: per_page)
  end
end

然后你可以在你的 View 中这样做:

<% @tournaments.each do |t| %>
  <% images = t.paginated_images(params[:page]) %>
  <% images.each do |image| %>
    <%= image_tag image %>
  <% end %>
  <%= will_paginate images %>
<% end %>

关于ruby-on-rails - Rails 中的 will_paginate 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23492822/

相关文章:

ruby-on-rails - 将分页 : How change default page in links

mysql - Rails 找到 :conditions

Ruby 数组减法,无需多次删除项目

ruby-on-rails - 约定 : if (! foo) 与除非 (foo)。 while (!foo) vs until (foo)

mysql - Mongoid 替代 MySQL 的 DateTime 字段工具,例如 select * from posts where HOUR(posted) = 01

ruby-on-rails-3 - Rails 3 升级 will_pagination 参数数量错误(2 为 1)

ruby-on-rails - will_paginate 的total_entries 无法正常工作rails 4

java - 似乎有多个层次的多方性?

ruby-on-rails - 不在数据库中的 CarrierWave 属性总是等于 nil

ruby-on-rails - Ruby 中的 Mechanize 和 SSLError