【发布时间】: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 页面会更容易,但出于其他原因我需要它来工作。
谢谢!!
【问题讨论】:
-
能否请您发布您的整个索引方法?
-
@posts是Post实例的集合,但pictures关联仅适用于Post的单个实例。您是否要显示所有帖子的所有图片,每页五张?如果是这样,您可能只想生成一个扁平化的帖子图片集合并对其进行分页。 -
把@pictures 放到 Post#show action... 而不是 index.... 它必须是 @post.pictures.paginate(..)
标签: ruby-on-rails ruby-on-rails-4 activerecord pagination