开发者

View criteria in Rails controller

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')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜