获取rails相关模型的所有数据

时间:2020-05-17 18:10:47

标签: ruby-on-rails rails-activerecord

我有一个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 fomat中的两个表中的所有信息,因为我将使用此url进行ajax调用。

有什么方法可以在活动记录查询中实现此sql吗?

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

1 个答案:

答案 0 :(得分:1)

您可以使用select 选择所需的字段:

<new dim with levels 1..7>

User.joins(:student_profile).select('users.*, student_profiles.*') 用于选择所有字段

*表中选择特定字段:

student_profiles

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