Convert Rails 4 has_many from condition with proc

2019-04-28 07:37发布

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.

2条回答
聊天终结者
2楼-- · 2019-04-28 08:02

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)

查看更多
相关推荐>>
3楼-- · 2019-04-28 08:08

I'd start with something like this:

has_many :subclass_point_analytics, -> { where("assessment_id = #{self.send(:assessment_id)}") }, :foreign_key => 'gid',  :dependent => :destroy
查看更多
登录 后发表回答