![](/img/trans.png)
[英]What is a syntax to query a first_name of employees and first_name of their managers?
[英]Rails simplify a query to get user profile's first_name
我想为申请人检索application.applicant.profile.first_name,但无法使用上述申请人检索个人档案attribute:first_name。
配置文件,应用程序通过外键user_id连接到用户。有人可以建议一种方法吗?
这是我的关联:
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'
这行是不正确的...
has_one :profile, -> { where role: 'user' }, class_name: 'User', dependent: :destroy
它应该是...
has_one :profile, -> { where role: 'user' }, dependent: :destroy
:profile
的class_name是Profile
但是您无需指定它,因为它可以通过符号从符号派生。
经过无数种排列和组合,例如多态,select&join语句,甚至通过提供SQL查询,终于意识到,就像我知道当前用户的user_id一样,它就像一个简单的语句一样简单:
<% post.applications.each do |papplication| %>
<%= Profile.find_by_user_id(papplication.user_id).first_name %> <% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.