简体   繁体   中英

Rails simplify a query to get user profile's first_name

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'     

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM