【问题标题】:Query to get all data from associated model on rails查询以从 Rails 上的关联模型中获取所有数据
【发布时间】:2020-05-17 18:10:47
【问题描述】:

我有一个User 模型和StudentProfile 模型关联

class User < ApplicationRecord
  has_one :student_profile 
end

class StudentProfile < ApplicationRecord
  belongs_to :user 
end

我想渲染两个表的所有字段。该操作的 SQL 命令是

select * from users join student_profiles on student_profiles.user_id = users.id

但是

User.joins(:student_profile)

仅显示User 表的字段。我需要 json 格式中两个表中的所有信息,因为我将使用此 url 进行 ajax 调用。

有没有办法在活动记录查询中实现这个sql?

select * from users join student_profiles on student_profiles.user_id = users.id

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    您可以使用select 选择您想要的字段:

    User.joins(:student_profile).select('users.*, student_profiles.*')
    

    * 用于选择所有字段

    或者student_profiles表中选择特定字段:

    User
      .joins(:student_profile)
      .select('users.*, student_profiles.first_name, student_profiles.last_name')
    

    但我建议您阅读有关活动模型序列化程序的信息,因为您处理的是 JSON。

    【讨论】:

    • 第一个对我来说已经足够了。我需要那个。-谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多