posted on Tuesday, June 29, 2010
This will increment "views" attribute of the post and save it to database, increment!(attribute, by=1):
@post.increment!(:views)
This will decrement "views" attribute of the post and save it to database, decrement!(attribute, by=1):
@post.decrement!(:views)
This will assign to attribute the boolean opposite of it:
@post.published # -> true
@post.toggle!(:published)
@post.published # -> false
class PostsController < ApplicationController
before_filter :find_post, :only => [:publish, :show]
def show
@post.increment!(:views)
end
private
def find_post
@post = Post.find(params[:id])
end
end
Reloading attributes from database, to get the latest values, reload(options = nil):
@post = user.posts.find(5)
user.posts.find(5).increment!(:views)
@post.views # -> 0
@post.reload
@post.views # -> 1
Reordering of already defined scope:
Post.scoped.collect {|p| p.id }
- 1
- 2
- 3
Post.scoped.reverse_order.collect {|p| p.id }
- 3
- 2
- 1