Mika
Mika

Reputation: 5845

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. 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.

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

Upvotes: 1

Views: 1266

Answers (2)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

In job_request.rb add the following association

belongs_to :user
belongs_to :job_request

belongs_to is used when you are storing foreign key of a particular model. When has_one is used at that time you are not storing foreign key of another table.

Query should be

JobRequest.includes (:user, :job).where ('job_requests.job_id = ? and job_requests.user_id = ? ', params [:id], current_user.id)

Upvotes: 2

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

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 :

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.

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. If there is a column called profile_id on the users table, we will say that a Profile has a User.

For further study you can read this article.

Upvotes: 1

Related Questions