查询以从 rails 上的关联模型中获取所有数据

Query to get all data from associated model on rails

我有一个 User 模型和 StudentProfile 模型协会是

class User < ApplicationRecord
  has_one :student_profile 
end

class StudentProfile < ApplicationRecord
  belongs_to :user 
end

我想渲染两者的所有字段 table。 SQL 操作命令是

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

但是

User.joins(:student_profile)

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

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

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

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

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

* 用于 selecting 所有字段

student_profiles中选择特定字段 table:

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

但我建议您阅读有关活动模型序列化器的内容,因为您正在处理 JSON。