Andrew Zelenets
Andrew Zelenets

Reputation: 59

Where is the right way to write Where AND condition query in Ruby?

Who can help me write the right WHERE AND condition? Or if it's right, what is the difference?

1.

get_primary_status = Trustee.select(:id).where(:secret_key => seckey, :user_id => user_id, :primary_trustee => '1')

2.

get_primary_status = Trustee.select(:id).where(:secret_key => seckey).where(:user_id => user_id).where(:primary_trustee => '1')

3.

get_primary_status = Trustee.select(:id).where('secret_key = (?) AND user_id = (?) AND primary_trustee = (?)', seckey, user, '1')

Upvotes: 2

Views: 137

Answers (3)

RedXVII
RedXVII

Reputation: 877

I'd recommend using the Squeel gem, even though ActiveRecord works fine here, if you were to have multiple ORs and ANDs in the query, the command is not always very readable

This is how your request would look in Squeel

Trustee.select(:id).where { (secret_key == seckey) & (user_id == my_user_id) &  (primary_trustee == '1') }

Upvotes: -1

Marek Lipka
Marek Lipka

Reputation: 51151

There is no difference between these three snippets (if you don't use any JOINS that can make column names in third one ambiguous).

You can confirm it by calling them in Rails console and looking at generated SQL code.

I think the first one is most readable.

Upvotes: 5

Denis Yagofarov
Denis Yagofarov

Reputation: 61

The first one.

For 2nd: as long, as you don't need dynamically add conditions, avoid chaining of 'where' functions.

For 3rd: whiting raw SQL may be good idea in some cases. But what if you will use SQLite for prototype, and PostgreSQL for going to production? Yep, they use SQL language as a standard, but Arel gives good abstraction over it.

Upvotes: 1

Related Questions