Rails has in default .next
. Is there .previous
method in ruby, should i define it myself?
"#{photo.id.previous}"
I have it defined in my Photo model and it works for my photo views, but this is being used in the User views. Does it need to be defined in the User Model?
users_controller.rb
def show
@user = User.find(params[:id])
@photos = @user.photos.order('created_at desc').paginate(page: params[:page], per_page: 12)
end
show.html.erb (users)
<% @photos.in_groups_of(3, false).each do |group| %>
<div class="row">
<% group.each do |photo| %>
<a data-toggle="modal" href=<%="#"+"#{photo.id}"%>>
<div class="col-xs-4 insta">
<%= image_tag(photo.picture.ad.url, class: "img-responsive") %>
</div>
</a>
<div class="modal" id=<%="#{photo.id}"%> tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
...
...
...
<a class="prev" data-dismiss="modal" data-toggle="modal" href=<%="#"+"#{photo.id.previous}"%>>
"Previous"
</a>
<a class="next" data-dismiss="modal" data-toggle="modal" href=<%="#"+"#{photo.id.next}"%>>
"Next"
</a>
user.rb
def previous
#.. ?
end
You can find this record like this:
class User
def self.previous_by_id(id)
where("id < ?", id).last
end
end
User.previous_by_id(5)
#=> #<User:0x0000000741b818 id: 4 .....>
Or if you want to define it like instance method:
class User
def previous
self.class.where("id < ?", id).last
end
end
Ruby already has this method. For eg:
1.pred
# => 0
Check out this for more detail
And Rails also supports this. For eg:
photo.id.pred
class User
def previous
self.class.where("id < ?", id).last
end
end
class User
def next
self.class.where("id > ?", id).first
end
end
href=<%="#"+"#{photo.previous.id}"%>>
href=<%="#"+"#{photo.previous.id}"%>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.