Question

I'm new to this RoR world,

I've many SELECT sql queries in my RoR Application, something like this

@replies  = Offerreply.find_by_sql ("SELECT * FROM offerreplies WHERE 
offer_id="+params [:offer_id])

Some are very simple like above and some are very complex JOINS. most of them are suffering from SQL Injection problem. So., How to Sanitize such SQL statements in RoR?

Edit: How to Handle same in SQL statements which has JOINS and Sub-queries? something like this

@to_be_approved=Beneficiary.find_by_sql("SELECT * FROM beneficiaries WHERE project_id="+params[:id]+" AND NOT id IN (SELECT beneficiaries.id FROM beneficiaries INNER JOIN beneficiaryloans ON beneficiaryloans.beneficiary_id=beneficiaries.id AND beneficiaryloans.hfi_id="+session[:id].to_s+" AND beneficiaries.status_id=4) AND cso_id IN(SELECT user_id FROM user_projects INNER JOIN users ON  user_projects.user_id=users.id AND users.user_type_id=2)")
Was it helpful?

Solution

If you're using Rails 3 (as your tag says), you can do it like this.

@replies  = Offerreply.where("offer_id = ?", params[:offer_id])

You can find more information at the Rails site.

edit: If you have more than one condition, you can do it like this.

@replies  = Offerreply.where("offer_id = ? AND second = ?", params[:offer_id], params[:second])

edit2: And see Micha's answer for multiple joins.

OTHER TIPS

Waynn Lue's answer is fine, but it doesn't show how to query on joined tables. You can do it like this:

Offerreply.joins(:offers).where('offers.id', params[:offer_id])

Or:

Offerreply.joins(:offers).where(:offers => { :id => params[:offer_id] })

Again: if you want to use Rails you really have to learn the Active Record Query Interface. Here's the paragraph on joins. Only use find_by_sql if there is no way of doing it via the "normal" interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top