简体   繁体   English

查询以从 rails 上的关联 model 获取所有数据

[英]Query to get all data from associated model on rails

I have one User model and StudentProfile model associations are我有一个User model 和StudentProfile model 关联是

class User < ApplicationRecord
  has_one :student_profile 
end

class StudentProfile < ApplicationRecord
  belongs_to :user 
end

I want to render all fields of both table.我想呈现两个表的所有字段。 SQL command for the action is SQL 动作命令是

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

But

User.joins(:student_profile)

shows only the fields of User table.仅显示User表的字段。 I need to all info from both table in json fomat as I'll use this url for an ajax call.我需要 json 格式的两个表中的所有信息,因为我将使用此 url 进行 ajax 调用。

Is there any way to realise this sql in active record query?有没有办法在活动记录查询中实现这个sql?

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

You can use select to select the fields that you want:您可以使用select到 select 所需的字段:

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

* is for selecting all fields *用于选择所有字段

Or Choosing specific fields from student_profiles table:或者student_profiles表中选择特定字段:

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

But I would suggest reading about active model serializers since you dealing with JSON.但我建议阅读有关活动 model 序列化程序的信息,因为您正在处理 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM