简体   繁体   中英

Ruby on Rails Model association

I am trying to make an application using Rails 3.2.14, but I can't wrap my head around the model associations that I have built so far. I have four models which are interconnected to give desired result but so far it hasn't been working.

  • Job with fields: user_id , title
  • Jobapplication with fields: job_id , user_id , isrefused
  • Resume with fields: user_id , profession

I am trying to extract all the jobs which a particular user has applied for using the jobapplication model in an instance variable for the view.

All tables containing foreign keys have belong_to associations along with has_many at the other end.

So far, I have tried like this in the controller:

def applied job
  @jobapplications = Jobapplication.where('user_id = ?', current_user.id)
  @jobs            = @jobapplications.jobs
end

The purpose is to find jobs for which the user has put in application for.

Should I redesign the models association?

The accessors can be greatly simplified if you write your model associations like this:

class User < ActiveRecord::Base
  has_many :jobs                  # jobs posted
  has_many :job_applications      # job applications posted
  has_many :applied_jobs, through => :job_applications, :source => :job  # jobs applied for
  has_one :resume
end

class Job < ActiveRecord::Base
  belongs_to :user
  has_many :job_applications
  has_many :applicants, :through => :job_applications, :source => :user   # applicants for this job
  has_many :applicant_resumes, :through => :job_applications, :source => :resume
end

class JobApplication < ActiveRecord::Base
  belongs_to :user
  belongs_to :job
  has_one :resume, :through => :user  # the resume for the application
end

class Resume < ActiveRecord::Base
  belongs_to :user
end

Now you can easily find the jobs a user applied for:

current_user.applied_jobs

Or all the applicants (users applying) for a specific job:

@job.applicants

And you can see a user's resume:

current_user.resume

Or an application's resume:

@job_application.resume

Or all resumes for those applying for a specific job:

@job.applicant_resumes

This looks okay:

@jobapplications = Jobapplication.where("user_id =?", current_user.id)

but not sure about this:

@jobs = @jobapplications.jobs

What's the jobs method?

try this:

#some_controller.rb

def applied_job #note the underscore!
  @jobapplications = Jobapplication.where("user_id =?", current_user.id)
end

and in the view

<% @jobapplications.each do |application| %>
  #list applications here
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM