开发者

View criteria in Rails controller

开发者 https://www.devze.com 2023-02-09 14:48 出处:网络
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 t

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

精彩评论

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