ruby on rails - How to get scope with polymorphic association -


i building rails 5 app , in app got 2 models. first 1 called timeoff , second 1 called approval.

i want timeoff objects got no approvals.

the time off model

class timeoff < applicationrecord    scope :not_approved, -> { self.approvals.size > 0 }    has_many :approvals, as: :approvable, dependent: :destroy  end 

the approval model

class approval < applicationrecord    belongs_to :approvable, polymorphic: true  end 

i calling this

timeoff.not_approved 

i error

nomethoderror: undefined method `approvals' #<class:0x007f9698587830> 

you're trying call approvals in class context, belongs instance of timeoff. example:

timeoff.approvals # doesn't work timeoff.first.approvals # works 

that's why undefined method error. think want database query here. go 2 ways - know of:

make 2 queries: find timeoffs have approvals , query other ones using not in

timeoff_ids = approval.where(approvable_type: 'timeoff').pluck(:approvable_id) timeoff.where.not(id: timeoff_ids) 

this may slow if tables big. or join on approvals table , filter id null:

timeoff.joins("left join approvals on timeoffs.id = approvals.approvable_id , approvals.approvable_type = 'timeoff'").where("approvals.id null") 

this should work, , may faster - should measure own data sure.

also, take @ question: how select rows no matching entry in table? there complete explanation of second query , other ways solve it.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -