1

I want to as that what will happen if I delete the models in the rails project and apply my SQL query, is it necessary to have a model to write Raw SQL queries.

2 Answers 2

4

is it necessary to have a model to write Raw SQL queries?

No, if you're using ActiveRecord, then you can use the ActiveRecord::Base.connection.execute and/or ActiveRecord::Base.connection.exec_query methods.

Similarly you can even run prepared statements relying on the ActiveRecord::Base.connection.raw_connection.prepare method that it inherits from your adapter.

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

4 Comments

can you help me to convert this activerecord query into raw sql fetched_transactions = Transaction.includes(:sender, :receiver).references(:sender, :receiver).where.not(main_type: 'refund_fee').where('receiver_wallet_id IN (?) OR sender_wallet_id IN (?) OR transactions.from LIKE ? OR transactions.to LIKE ?', wallets, wallets, wallets.to_s, wallets.to_s).where.not(main_type: 'Sale Issue', status: %w[pending issue_failed pending_transfer]).to_sql.where(conditions)
That can be a separate question @HamzaAmin, feel free to create it.
my questions limit is over so that's why i asked in the comment.
Check this stackoverflow.com/help/answer-bans. I'm happy to help with any question, but one at a time.
0

Providing you have run a migration and the table is present in your database, it is not necessary to have the model file present locally if you want to run raw sql queries.

In doing this you will miss out on a lot of the perks ActiveRecord/Ruby objects provide and make the process much more error prone and vulnerable to sql injection attacks.

1 Comment

This answer would be much better if you actually said how to do it. Just like the other one did.

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.