Reputation: 7043
Due to specific results I would like to render, I am currently using scopes in my views. I know it is probably not the best idea, but I honestly have no clue how to refactor it in a proper way. Would appreciate any advice!
Controller
@categories = Category.all
Models
#post.rb
scope :published, -> { Post.all.where(published: true).order('created_at DESC') }
#category.rb
def published_posts
posts.published
end
View
@categories.each do |category|
category.published_posts.each do |post|
... # continue rendering post by post
as you can see I am using published_posts right in my view. Do you think this is ok, or should I refactor it somehow?
Upvotes: 0
Views: 47
Reputation: 3057
More concise code would result if you refactor by removing the helper and using the scope directly.
category.posts.published.each do |post|
Using scopes in views is considered a Rails best practice. Clean. Concise. Modular.
Upvotes: 0
Reputation: 302
Well it depends. It is okay to call scope in views. It is as good as calling method on object. Now it depends you would like to do some preprocessing on posts before passing to view or decorate them, then you can move this logic to controller.
Another example would be, suppose you have promoted posts then you would like to add more logic fetch posts and pass it to views.
At the end of the day, I would like to have less business logic in views. Just pass the data and render it.
Upvotes: 1