簡體   English   中英

查詢以從 rails 上的關聯 model 獲取所有數據

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

我有一個User model 和StudentProfile model 關聯是

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

您可以使用select到 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')

但我建議閱讀有關活動 model 序列化程序的信息,因為您正在處理 JSON。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM