Rails simplify a query to get user profile's first_name

73 views Asked by At

I want to retrieve application.applicant.profile.first_name for the applicant and I'm not able to retrieve the profile attribute:first_name using applicant above.

Profile, application are connected by foreign key: user_id to user.Can someone suggest a way?

Here are my associations:

user.rb

class User < ApplicationRecord
 has_many :applications
 has_one :profile, -> { where role: 'user' }, dependent: :destroy

profile.rb

class Profile < ApplicationRecord
    belongs_to :user, :class_name => 'User', :foreign_key => 'user_id'

job.rb

class Job < ApplicationRecord
    has_many :applications, :dependent => :destroy
    has_many :applicants, :through => :applications, :class_name => 'User'

application.rb

class Application < ApplicationRecord
  belongs_to :job
  belongs_to :applicant, :class_name => 'User', :foreign_key => 'user_id'     
2

There are 2 answers

2
SteveTurczyn On

This line isn't correct...

 has_one :profile, -> { where role: 'user' }, class_name: 'User', dependent: :destroy

It should be...

 has_one :profile, -> { where role: 'user' }, dependent: :destroy

The class_name for :profile is Profile but you don't need to specify it as it can be derived from the symbol by rails.

0
Means On

After numerous permutations and combinations such as polymorphic, select & join statement or even by providing a SQL query, finally realised that it was as simple as a single statement as I knew the user_id of current user:

<% post.applications.each do |papplication| %>
  <%= Profile.find_by_user_id(papplication.user_id).first_name %> <% end %>