If a post has a 开发者_开发技巧status
column in the database that has either value draft
or published
, how do I define index
in my controller to show only status
with published
? I know I can achieve this using if-else
in my view, but I wonder if there is a better approach in the controller.
Thanks.
If you plan to use often a finder for published posts, you may prefer using a named scope rather than a conditions in you controllers.
app/models/post.rb :
named_scope :published, :conditions => {:status => 'published'}
app/controllers/posts_controller.rb
@posts = Post.published
In controller file, modify index method: replace the default @books = Book.all
with @books = Book.where(:status => 'published')
精彩评论