Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Rails 4 has_many from condition with proc to where

I have the following working has_many with a proc to capture a parameter for context:

has_many :subclass_point_analytics, :conditions =>  proc {"assessment_id = #{self.send(:assessment_id)}" }, :foreign_key => 'gid',  :dependent => :destroy

I am using Rails 4 and it is (rightfully) complaining about use of :conditions. After 30 minutes and lots of tries I cannot figure out how to convert :conditions to -> { where ... } format. I would appreciate someone with knowledge of proc syntax to help me get that correct.

like image 691
TJChambers Avatar asked Oct 09 '13 17:10

TJChambers


1 Answers

Just do this:

has_many :subclass_point_analytics, -> (object) { where("assessment_id = ?", object.assessment_id) }, :foreign_key => 'gid',  :dependent => :destroy

object is your actual instance. Also, watch out: the callable has to be the first thing (:conditions tend to be at the end)

like image 98
Thomas Avatar answered Sep 21 '22 15:09

Thomas