Reputation: 725
I try to follow RESTfull approach in controllers, but sometimes I need action which won't fit into default ones. E.g. I have an index action rendering all articles which is
def index
@articles = Article.all
end
but what if I also want search them? should I create separate actions for it, or should I bloat existing controller, like:
def index
if params[:search]
@articles = Article.where(id: params[:search_id])
else
@articles = Article.all
end
end
What is the right way?
Upvotes: 1
Views: 52
Reputation: 32933
I would keep it in index. If you want to keep it clean and standardise it you could change the controller code thus:
def index
@articles = Article.search(params[:search])
end
and then add a class method in Article
class << self
def search(options={})
if options.blank?
return self.all
else
..other search logic
end
end
end
Note that the example you gave for a search doesn't really make sense as it's specifying the id of the article. If you already know the id then that's not really a search: you might as well just go to the show page for the article.
Upvotes: 0