[英]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. 我正在尝试使用Rails 3.2.14创建一个应用程序,但是我无法将我迄今为止所建立的模型关联包围起来。 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
Job
包含以下字段: user_id
, title
Jobapplication
with fields: job_id
, user_id
, isrefused
Jobapplication
: job_id
, user_id
, isrefused
Resume
with fields: user_id
, profession
Resume
: 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. 我正在尝试提取特定用户已在视图的实例变量中使用
jobapplication
模型申请的所有作业。
All tables containing foreign keys have belong_to
associations along with has_many
at the other end. 包含外键的所有表都
belong_to
协会沿has_many
在另一端。
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? jobs
方法是什么?
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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.