Has_many condition with polymorphic association

A small thing that is bugging me. I have:

class Job < ApplicationRecord 
   has_many :activities, as: :actor
end
class Activity < ApplicationRecord 
   belongs_to :actor, polymorphic: true
end

Before I made Activity Polymorphic in Job I had:

has_many :bound_activities,  -> {where("start_date is not null and end_date is not null")}, :class_name=>'Activity'

I have changed this to a method

def bound_activities 
   activities.where("start_date is not null and end_date is not null" )
end

I would really like to make this a has_many as before, but I cannot find a way to tell rails this is using polymorphic foreign key. Is this possible?

Thanks

I was also having to deal with polymorphic associations and was wondering: would this work for you?

has_many :activities,  -> {where("start_date is not null and end_date is not null")}, as: :actor

From what I read in the docs, you could still pass the prop. Let me know if you got the results you wanted, I’m curious about it.

1 Like

thanks for you response, sorry for delay in getting back, but I was in the middle of a large refactoring change and only just spotted your reply. You are correct, it does now work, needed both as: :actor and class_name: ‘Activity’

has_many :bound_activities,  -> {where("a_start_date is not null and a_end_date is not null")}, as: :actor, class_name: 'Activity'

Again thanks for taking the time to reply.