0

Is this, the best way to sanitize 'join' params inside a Controller in Rails 4?

assume:

user_name = params[:user_name]

.

# That's the only way that I can figure this out:
@result = Agenda.joins("LEFT JOIN meetings AS me ON meetings.agenda_id = agendas.id WHERE me.name = #{Agenda.sanitize(user_name})"

I have tried this but don't works because 'joins' expect tables after each ',':

@result = Agenda.joins("LEFT JOIN meetings AS me ON meetings.agenda_id = agendas.id WHERE me.name = ?", user_name)

Note: This is just a bit of the code to explain the problem, in the full code I really have to use the LEFT JOIN.

DoctorRu
  • 1,063
  • 1
  • 13
  • 15
  • 1
    Take away the WHERE clause, it could be added then, like `Agenda.joins('LEFT JOIN meetings ON meetings.agenda_id = agendas.id').where('meetings.name = ?', user_name)`. – Sebastián Palma Feb 28 '18 at 22:07
  • 6
    Why not use `Agenda.joins(:meetings).where(meetings: { name: user_name })`? – MrYoshiji Feb 28 '18 at 22:13
  • As this made me curious: i came across this question where the final consensus seems to be that DBs will most likely have the same performance on queries with the WHERE condition inside as well as outside of the JOIN. See https://stackoverflow.com/questions/1018952/condition-within-join-or-where – neongrau Mar 02 '18 at 09:00
  • Thanks by the comments about the query, I will really think about rewrite them using 'where'. – DoctorRu Mar 02 '18 at 15:32

1 Answers1

0

I found a better solution using

Model.send(:sanitize_sql_array, < query >)

eg:

user_name = params[:user_name]

join = "LEFT JOIN meetings AS me 
        ON meetings.agenda_id = agendas.id 
        WHERE me.name = ?", user_name)"

join = Agenda.send(:sanitize_sql_array,join)

@result = Agenda.joins(join)

In this format, you can use as many parameters as you need with any type of query.

DoctorRu
  • 1,063
  • 1
  • 13
  • 15