Reputation: 119
I've got the following models in my Rails app:
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
So a Post has_many Pictures. On my Post#index view, I use the following code to iterate through the posts and display the thumbnail for each of their pictures:
<% @posts.each do |post| %>
<% post.pictures.each do |picture| %>
<li>
<%= link_to image_tag(picture.image.url(:thumb)), picture_path(picture)%>
</li>
<% end %>
In order to limit the number of pictures displayed on each page, I'm attempting to implement pagination by using the following code in my Posts controller:
@pictures = @posts.pictures.paginate(:per_page => 5, :page => params[:page])
This gives the following error:
undefined method `pictures' for #<Post::ActiveRecord_Relation:0x007fc960f698a8
What am I doing wrong here? How could I fix this?
Also, I know it seems like it would be easier to just use the Pictures#index page, but I need this to work for other reasons.
Thanks!!
Upvotes: 0
Views: 849
Reputation: 18784
@posts
is a relation (array-like object), and it doesn't have a method named pictures
.
I'm not sure why you are paginating the pictures attached to each post on an index view, but you might be doing a carousel or something, so it may be valid, but if that's the case, you'll need to paginate in the view (or build a more complex data structure in your controller):
<% @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 %>
Upvotes: 1