【问题标题】:Using will_paginate with a has_many relationship in Rails 4在 Rails 4 中使用 will_paginate 和 has_many 关系
【发布时间】:2015-10-12 20:54:46
【问题描述】:

我的 Rails 应用中有以下模型:

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :pictures, :dependent => :destroy
end


class Picture < ActiveRecord::Base
  belongs_to :post
  has_many :comments
  has_attached_file :image, styles: { medium: "800x800>", thumb: "225x225#" }
  validates_attachment_content_type :image, :content_type => ["image/jpg","image/jpeg","image/png"]
end

所以一个帖子有_许多图片。在我的 Post#index 视图中,我使用以下代码遍历帖子并显示每张图片的缩略图:

<% @posts.each do |post| %>
  <% post.pictures.each do |picture| %>
      <li>
        <%= link_to image_tag(picture.image.url(:thumb)), picture_path(picture)%>
      </li>
<% end %>

为了限制每页显示的图片数量,我试图通过在我的 Posts 控制器中使用以下代码来实现分页:

@pictures = @posts.pictures.paginate(:per_page => 5, :page => params[:page])

这会产生以下错误:

undefined method `pictures' for #<Post::ActiveRecord_Relation:0x007fc960f698a8

我在这里做错了什么?我该如何解决这个问题?

另外,我知道似乎只使用 Pictures#index 页面会更容易,但出于其他原因我需要它来工作。

谢谢!!

【问题讨论】:

  • 能否请您发布您的整个索引方法?
  • @postsPost 实例的集合,但pictures 关联仅适用于Post 的单个实例。您是否要显示所有帖子的所有图片,每页五张?如果是这样,您可能只想生成一个扁平化的帖子图片集合并对其进行分页。
  • 把@pictures 放到 Post#show action... 而不是 index.... 它必须是 @post.pictures.paginate(..)

标签: ruby-on-rails ruby-on-rails-4 activerecord pagination


【解决方案1】:

@posts 是一个关系(类数组对象),它没有名为 pictures 的方法。

我不确定您为什么要在索引视图上对附加到每个帖子的图片进行分页,但您可能正在做轮播或其他事情,所以它可能是有效的,但如果是这种情况,您需要在视图中分页(或在控制器中构建更复杂的数据结构):

<% @posts.each do |post| %>
  <% post.pictures.paginate(:per_page => 5, page => params["post_#{post.id}_pictures_page"]).each do |picture| %>
    <li>
      <%= link_to image_tag(picture.image.url(:thumb)), picture_path(picture)%>
    </li>
  <% end %>
<% end %>

【讨论】:

  • 您实际上是正确的,因为我一开始就完全错误地解决了我的问题。我真正需要的是让帖子接受图片的嵌套属性,然后使用图片索引并对其进行分页。感谢您的帮助!
猜你喜欢
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多