1

I am trying to create a resume builder. Inside the resume, I would like to display the first corresponding Job title to a specific User in the show.html.erb.

I first made sure that Jobs has the user_id foreign key..

Schema

create_table "jobs", force: true do |t|
    t.string   "title"
    t.string   "company"
    t.date     "date_start"
    t.date     "date_end"
    t.boolean  "current"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
    t.integer  "career_id"
end

..and the relationships are like so:

User Model

class User < ActiveRecord::Base
  
        has_one :career
        has_many :jobs, through: :career
end

Job Model

class Job < ActiveRecord::Base
    belongs_to :user
    has_many :descriptions
end

Controller

def show
  @user = User.find(1)
end

What is the best way to go about this? I was able to display other elements such as Name and Contacts on the same Show View page. I have tried a ton of different lines but currently have this...

Show View

<%= @user.jobs.first.title %>
Community
  • 1
  • 1
shroy
  • 918
  • 2
  • 10
  • 24

2 Answers2

1

Your Job model has belongs_to :user, which would mean your jobs table needs a user_id attribute.

I don't know how your Career model looks like, but it seems you don't need

has_many :jobs, through: :career

if you're tying the job directly to the user via user_id (which should be added to your jobs table). In other words,

has_many :jobs

might just work. However, if you need to stick to Career, then make sure that

class Career < ActiveRecord::Base
  belongs_to :user
  has_many :jobs
end

And then, from your view do:

<%= @user.jobs.first.title %>
Marcelo Ribeiro
  • 1,718
  • 1
  • 13
  • 27
1

Join Table

What you're looking at is a has_many :through relationship:

enter image description here

As such, you'll be better with the following setup -

#app/models/user.rb
class User < ActiveRecord::Base
   #fields id | etc | etc | etc | created_at | updated_at
   has_many :careers
   has_many :jobs, through: :careers
end

#app/models/career.rb
class Career < ActiveRecord::Base
   #fields id | job_id | career_id | created_at | updated_at
   belongs_to :job
   belongs_to :career
end

#app/models/job.rb
class Job < ActiveRecord::Base
   #fields id | title | created_at | updated_at
   has_many :careers
   has_many :users, through: :careers
end

This will give you the ability to call the following:

#app/controllers/users_controller.rb
class UsersController < ApplicationController
   def show
      @user = User.find
   end
end

#app/views/users/show.html.erb
<%= @user.jobs.first.title %>
Richard Peck
  • 76,116
  • 9
  • 93
  • 147