Constructing a Rails ActiveRecord where clause

How about:

def index
  author_id = params[:author_id]

  @posts = Post.scoped

  @post = @post.where(:author_id => author_id) if author_id.present?

  @post = @post.where(:some_other_condition => some_other_value) if some_other_value.present?
end

Post.scoped is essentially a lazy loaded equivalent to Post.all (since Post.all returns an array immediately, while Post.scoped just returns a relation object). This query won't be executed until you actually try to iterate over it in the view (by calling .each).


Mmmh, the best approach you want to use can be to spread this in 2 actions

def index
   @post = Post.all
end

def get
  @post = Post.where("author=?", params[:author_id])
end

IMHO it has more sense if you think about a RESTful API, index means to list all and get (or show) to fetch the requested one and show it!