问题
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.
回答1:
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)
回答2:
I'd start with something like this:
has_many :subclass_point_analytics, -> { where("assessment_id = #{self.send(:assessment_id)}") }, :foreign_key => 'gid', :dependent => :destroy
来源:https://stackoverflow.com/questions/19279289/convert-rails-4-has-many-from-condition-with-proc-to-where