Convert Rails 4 has_many from condition with proc to where

主宰稳场 提交于 2020-01-13 09:17:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!