Kelvin
Kelvin

Reputation: 2288

Rails association for has one/belongs to vs has many/belongs to

I want to create two tables, one is Job and one is JobType.

Each Job has one job_type ie. Temp, Parttime or Fulltime.

class Job < ApplicationRecord
  has_one :job_type
end

class JobType < ApplicationRecord
  belongs_to :job
end

So my job_type table will look like this

id  type    job_id
1   temp      1
2   temp      2
3   fulltime  3
4   temp      4

It seems redundant...

Should I instead be doing, job belongs to job_type and job_type has many jobs like this?

id   name   job_type_id
1   waiter    1
2   waiter    2
3   clerk     1

id   type  
1    temp
2    fulltime

I'm confused. Any help is appreciated. Thanks.

Upvotes: 0

Views: 704

Answers (3)

Oxagile Bhavesh
Oxagile Bhavesh

Reputation: 1

Ruby is just a simple programming language. It totally works as we speak.

For eg: A Posts has_many Comments and Comments belongs_to Post.

Over here u can clearly see that pluralization over here tells us that, there are many comments for a particular post. The same idea works with has_one relation, User has_many Votes, and Votes belongs_to User. So therefore in your case i suggest you to write your association as job has_many types and job_types belongs to job.

So the job_types table of here will be using the primary key of your table jobs as foreign key for normaliziation of data.

Upvotes: 0

kiddorails
kiddorails

Reputation: 13014

This problem fits to many-to-many relationship.
A job has_many job_types, and any job_type can has_may jobs.

For this you will need a join table - jobs_jobs_types.

Your data will then look like:

jobs
id   name   
1   waiter  
2   clerk   

jobs_types
id   type  
1    temp
2    fulltime

jobs_jobs_types
job_id job_type_id
1 1
1 2
2 1

I will leave the code for you. :) You can get additional help in this Railscast.

Upvotes: 0

Rahul2692
Rahul2692

Reputation: 344

One Job can have many job types, the association will be like

class Job < ApplicationRecord
  has_many :job_type
end

class JobType < ApplicationRecord
  belongs_to :job
end

Otherwise you can give association like one job has many job_types and one job_type has many jobs.

class Job < ApplicationRecord
  has_and_belongs_to_many :job_type
end

class JobType < ApplicationRecord
  has_and_belongs_to_many :job
end

Upvotes: 1

Related Questions