[英]Rails nested includes and belongs_to vs. has_one
I am writing an application for a job board. 我正在为求职板写一份申请表。 There is a
Users
table where users can post jobs or request to be awarded jobs. 有一个
Users
表,用户可以在其中发布工作或请求获得工作。 Therefore my Jobs
table has a user_id field for the posting user and a relationship to a Job_requests
table that has a job_id and a user_id but here the user_id is the requesting user's id. 因此,我的
Jobs
表具有发布用户的user_id字段以及与具有job_id和user_id的Job_requests
表的关系,但此处user_id是请求用户的id。
I am trying to show a job posted by a user: 我正在尝试显示用户发布的工作:
current_user.jobs.find(params[:id])
including the requests for that job: 包括对该工作的要求:
current_user.jobs.includes(:job_requests).find(params[:id])
but also including the details for the requesting user: 但也包括请求用户的详细信息:
current_user.jobs.includes(job_requests: :user).find(params[:id])
The first two work but the third crashes with the following error: 前两个工作但第三个崩溃,出现以下错误:
SQLException (no such column: users.job_request_id)
I know there is no such column I am looking for the details of the user that posted the request. 我知道没有这样的专栏我正在寻找发布请求的用户的详细信息。
Model Association 模特协会
User
has_many :jobs, dependent: :destroy
has_many :job_requests
Job
belongs_to :user
has_many :job_requests
JobRequest
has_one :user
has_one :job
In job_request.rb add the following association 在job_request.rb中添加以下关联
belongs_to :user
belongs_to :job_request
belongs_to
is used when you are storing foreign key of a particular model. 在存储特定模型的外键时使用
belongs_to
。 When has_one
is used at that time you are not storing foreign key of another table. 当你在那时使用
has_one
时,你不存储另一个表的外键。
Query should be 查询应该是
JobRequest.includes (:user, :job).where ('job_requests.job_id = ? and job_requests.user_id = ? ', params [:id], current_user.id)
For the following associations: 对于以下关联:
# User
has_many :jobs, dependent: :destroy
has_many :job_requests
# Job
belongs_to :user
has_many :job_requests
# JobRequest
belongs_to :user
belongs_to :job
Your query will be: 您的查询将是:
current_user.jobs.includes(job_requests: :user).find(params[:id])
belongs_to
& has_one
: belongs_to
& has_one
:
The only difference is what side of the relationship you are on. 唯一的区别是你所处的关系的哪一方面。 If a
User
has a Profile
, then in the User
model you need to have has_one :profile
and in the Profile
model you need to have belongs_to :user
. 如果
User
具有Profile
,则在User
模型中您需要具有has_one :profile
并且在Profile
模型中您需要拥有belongs_to :user
。
You can determine who has the other object by looking at where the foreign key is. 您可以通过查看外键的位置来确定谁拥有其他对象。 You can say a
User
has a Profile
because the profiles
table has a user_id
column. 您可以说
User
具有Profile
因为profiles
表具有user_id
列。 If there is a column called profile_id
on the users
table, we will say that a Profile
has a User
. 如果在
users
表上有一个名为profile_id
的列,我们会说Profile
有一个User
。
For further study you can read this article . 如需进一步研究,您可以阅读本文 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.