0

I'm trying to do a filter with a where clause and indicating the table.

Currently I'm using this, that only works if it's the exact same username:

@diagnostics = Diagnostic.scoped

@diagnostics = @diagnostics.includes(:user).where(tbl_users: { username: "#{params[:search]}" }) if params[:search_by] == 'by_user'

I'm trying to do a search where it can be use with a like, and its not working:

@diagnostics = Diagnostic.scoped

@diagnostics = @diagnostics.includes(:user).where(tbl_users: { username: "%#{params[:search]}%" }) if params[:search_by] == 'by_user'

Any solutions ?

Thanks.

SQB
  • 3,926
  • 2
  • 28
  • 49
Alejo Amiras
  • 67
  • 1
  • 8
  • Take a look at [How to do a LIKE query in Arel and Rails 3?](http://stackoverflow.com/questions/4430578/how-to-do-a-like-query-in-arel-and-rails-3). That should answer your question. – mario Jun 24 '13 at 19:07
  • The problem of doing .where('QUERY') is that I no longer indicate the table. Though I tried to declare the variable before using it on the query. And it didn't worked. – Alejo Amiras Jun 24 '13 at 19:11

2 Answers2

0

Try this.

@diagnostics = Diagnostic.scoped

@diagnostics = @diagnostics.includes(:user).where("users.username like '%?%'", params[:search]) if params[:search_by] == 'by_user'
usha
  • 28,973
  • 5
  • 72
  • 93
0

This is how you can do it:

@diagnostics = Diagnostic.scoped

@diagnostics = @diagnostics.includes(:user).all(:conditions => ['user_name LIKE ?', "%#{@q}%"])
Ankur
  • 5,086
  • 19
  • 37
  • 62