vidur punj
vidur punj

Reputation: 5861

Not able to make relationship correctly the rails way or a polymorphic relation ship?

I am using rails 5 and Ruby 2.3
I have a model name User created using the devise which can create jobs so the migration used for this is:

rails g model job user:references cader_id:integer

These jobs can be completed by the other user's with role Cader. When a Cader completed a job In it I store the user_id of that user in the job table as cader_id which is integer

What should be the correct way of doing it in the rails with proper indexing. So In case I want to search all jobs completed by the user they get searched fast the indexing.

I can search all jobs created by that user like

user.jobs

similarly to search the user of a particular job that can be searched using

job.user

How can, I search all jobs completed by the user as user as Cader like

cader.completed_jobs or user.completed_job 

and to search for the particular Cader who completed the job like

job.cader

Thank in advance

for now to search Cader that completed a Particular job I have written the class method like

 def cader?
    cader = User.find(self.cader_id)
 end     

Upvotes: 1

Views: 31

Answers (1)

uday
uday

Reputation: 1481

You can write a instance method completed_jobs in user model and fetch the completed_jobs by that user like this.

def completed_jobs
  Job.where(cader_id: id)
end

And to search for the particular cader change you're class method to job instance method as you're querying for a particular job instance.

Add index on cader_id to improve the search results

Upvotes: 1

Related Questions