Abhradip
Abhradip

Reputation: 413

issues related find_by_sql in rails

I am using Rails 4 and I need to use find_by_sql in my active record model.Now I am facing two serious problems. First one is that it does not give me a particluar data whether it is giving #Employee:0x0000000b2a1718 as result. My model name is Employee and tbale name is employees. I am using pg.

Please tell me is there any solution.

Second problem is that how can I write any rails variable with in the sql query used in find_by_sql. For example I want to execute find_by_sql("select firstname from employee where id=@var"), where @var is a ruby variable.

The actual query I need to execute is select firstname from employee where comapact_string like %@var% using find_by_sql.

Upvotes: 0

Views: 272

Answers (1)

tadman
tadman

Reputation: 211700

There's degrees of customization when making a query. The simplest form is where you can use the built-in finders:

Employee.where(id: @var).pluck(:first name)

That will do a direct match, and if one's found, give you the first_name column value. No model is produced with pluck.

If you want to do an approximate match with LIKE you write out the WHERE clause more formally:

Employee.where('id LIKE ?', "%{@var}%").pluck(:first_name)

It's rare you need to write out an entire query with find_by_sql, but if you do you must be extremely cautious about what data you put in the query. It's strongly recommended to use placeholder values whenever possible, and if you absolutely must bypass this, escape everything no matter the source.

Upvotes: 3

Related Questions