2

I have this code

Language.all.map{|l|[l.language, l.accounts.joins(:children).where("accounts.id IN (?)", @accounts.ids).uniq.count]}

I am trying to get this as output

[["eng", 5] ["span", 3] ["ital", 4] ... ]

I want to write it as a raw query.

I tried this,

ActiveRecord::Base.connection.execute("select languages.language, (SELECT COUNT(*) FROM accounts where accounts.language_id = languages.id) from languages").values

but i need to pass accounts.ids dynamic.. like this

select languages.language, (SELECT COUNT(*) FROM accounts where accounts.language_id = languages.id AND (accounts.id IN (#{@accounts.ids})) from languages"

when i tried to pass accounts.id IN #{@accounts.ids} i am getting error (accounts.id IN ([2839, 284.. .. this should have been IN (2839, 284..) instead, it is taking array.

How to pass it dynamically ?

3 Answers 3

3

You can try:

"... accounts.id IN (#{@accounts.ids.join(',')})"

Hope it helps.

Sign up to request clarification or add additional context in comments.

8 Comments

nope. getting PG::syntax error. it takes the whole thing as string
Oh, sorry, I think you use Mysql.
Did you forgot a ")" in query ?
no. syntax error was not because of ')' .. but for strings (" 1, 2, 3 ... ")
I don't know where " come from? It should be ... accounts.id IN (1, 2, 3).
|
1

The above 2 answers won't work if you are attempting to use an array of strings in a raw sql query. For a raw sql statement, you can use ActiveRecord's sanitize_sql_array method.

languages = ['eng', 'span', 'chin', 'ital']
base_query = "SELECT * FROM languages WHERE id IN (?)"
sanitized_query = ActiveRecord::Base.send :sanitize_sql_array, [base_query, languages]
ActiveRecord::Base.connection.execute(sanitized_query)

1 Comment

Very helpful, the change from an id to an uuid based system are tricky.
0

You can use where(id: @accounts.ids) or where("account.ids": @accounts.ids) or where("account.ids IN ?, @accounts.ids). I believe ActiveRecord should understand all of them.

1 Comment

yes. i know but i am trying to map another table records to get in specific format [[a, b] [c, d]]. it results in low performance since there are large number of records.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.