【问题标题】:Rails simplify a query to get user profile's first_nameRails 简化查询以获取用户个人资料的名字
【发布时间】:2016-12-12 23:21:58
【问题描述】:

我想检索申请人的 application.applicant.profile.first_name,但我无法使用上面的申请人检索个人资料属性:first_name。

个人资料,应用程序通过外键连接:user_id到用户。有人可以建议一种方式吗?

这是我的联想:

用户.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'

应用程序.rb

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

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-5 model-associations


    【解决方案1】:

    这行不正确...

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

    应该是……

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

    :profile 的 class_name 是 Profile,但您无需指定它,因为它可以通过 rails 从符号派生而来。

    【讨论】:

    • 酷,这解决了你的问题吗?
    • 我在下面给出了答案。您的更新只是我在输入时犯的一个错误。
    【解决方案2】:

    经过多态、select&join语句甚至提供SQL查询等无数次排列组合,终于意识到只要我知道当前用户的user_id,就这么简单:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-18
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多