Monday, April 23, 2012

Rails 3, Ransack and additional query criteria

I'm not exactly sure what the name of what I'm doing is so "additional query criteria" is what it came down to.

I have a table, I want to let users search through it but I only want them to search their records.

I'm using ransack for the searching and it's quite nice, it let me get the search up and running very quickly and it has more power than I really need.  What it didn't have was the ability to require a search term to be a specific value.  I should rephrase, the documentation did not have this.  Without this ability my users will search through everyones data and see things they shouldn't.

Normally I'd use a scope or something like it to make sure user_id = current_user.user_id but how do I do this with ransack?

The answer I'm currently using is to high-jack the query parameter and add my criteria before passing it on to the search method of my model.

That looks something like this:


if params[:q]
  params[:q]["user_id_eq"] = current_user.id
  @q = Customer.search(params[:q])
  @customers = @q.result(:distinct => true)
end

And that's it, now my query has my additional requirements tacked on.

[edit]

OK, so I guess I'm an idiot.  https://github.com/ernie/ransack/wiki/Basic-Searching clearly shows how to do this.  The above could probably be shortened to

  @q = Customer.search(params[:q].merge({"user_id_eq" => current_user.id})

Or something like that anyway

No comments:

Post a Comment