1

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     
Javier Menéndez Rizo
  • 2,138
  • 3
  • 12
  • 22
vidur punj
  • 5,019
  • 4
  • 46
  • 65

1 Answers1

1

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

uday
  • 1,421
  • 10
  • 19
  • yes, that can be done by making the instance method in the user class, But when the jobs number in millions the it will search 1 million records one by one to get all the jobs done by that particular Cader which is very time consuming, I want to do it by using indexing – vidur punj Feb 06 '19 at 10:21
  • that is why i mentioned to add index on `cader_id` in Job class. – uday Feb 06 '19 at 10:27