1

I am trying to query the database as such because of a rails3-jquery-autocomplete gem as talked about in this question Rails gem rails3-jquery-autocomplete: How do I query multiple fields

User.select("first_name, last_name, login, id").where(["CONCAT_WS(' ', first_name, last_name, login) LIKE ?", "%#{parameters[:term]}%"])

This works fine for what I need it to do but I feel like having explicit MYSQL code within my rails app is dirty and I was wondering if there was a database agnostic way of formulating the above query? If not is there a database that doesn't suport some sort of concatenate function?

I can't use a virtual attribute because the gem needs to query the database.

Alternatively I was going to add an extra column called full_name to the User model itself and use virtual attributes to separate it into first_name and last_name but would prefer another solution.

Community
  • 1
  • 1
cr0atIAN
  • 949
  • 10
  • 22

2 Answers2

2

I would to it the way you are doing. The virtual attribute seems to me a very good solution. So you are able to decouple the database from your application logic. Think about changing you db backend.

imho

otherwise - is a concate in the select field with an alias working?

Something like concate( firstname, ' ', ... ) as virtualfieldname ...?

devanand
  • 5,116
  • 2
  • 20
  • 19
2

Thanks wkaha for giving advice. It turns out it was a pretty silly question. After some reading on ActiveRecord I've learned that there is not way that I can use it to query with a LIKE modifier which is crucial for me so I left it the way it is. In case I end up switching to Postgres I will just change it to pipe concatenation.

cr0atIAN
  • 949
  • 10
  • 22