0

I have updated this question

I have the following SQL scope in a RAILS 4 app, it works, but has a couple of issues.

1) Its really RAW SQL and not the rails way 2) The string interpolation opens up risks with SQL injection

here is what I have:

scope :not_complete -> (user_id) { joins("WHERE id NOT IN 
(SELECT modyule_id FROM completions WHERE user_id = #{user_id})")}

The relationship is many to many, using a join table called completions for matching id(s) on relationships between users and modyules.

any help with making this Rails(y) and how to set this up to take the arg of user_id with out the risk, so I can call it like:

Modyule.not_complete("1")

Thanks!

1 Answers1

0

You should have added few info about the models and their assocciation, anyways here's my trial, might have some errors because I don't know if the assocciation is one to many or many to many.

scope :not_complete, lambda do |user_id|
  joins(:completion).where.not(   # or :completions ?
    id: Completion.where(user_id: user_id).pluck(modyule_id)
  )
end

PS: I turned it into multi line just for readability, you can change it back to a oneline if you like.

Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89
  • Good point, I had the relationship details in there and took them out when I updated, its m-2-m using a join table called completions. This looks right I will give it a shot. My biggest issue being a junior is that I can struggle through the SQL but don't always know how to build the aRel the match. –  Apr 27 '15 at 15:33