获取与Rails相关的模型的所有数据

问题描述 投票:0回答:1

我有一个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

我有一个User模型,并且StudentProfile模型关联是类User

您可以使用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以来,我建议阅读有关活动模型序列化程序的信息。

ruby-on-rails rails-activerecord
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.