簡體   English   中英

Rails 5-如何從數組轉換為activerecord關系?

[英]Rails 5 - How to convert from array to activerecord relation?

在Rails 5中,我編寫了一個查詢,例如User.where("id = #{current_user.id}").include_associations.order(created_at: :desc)

這將返回類似[#<User id: 15, name: "Shruthi", ...>]

我怎樣才能只在這里獲得activerecord數據(不需要數組)? 我想要一個像#<User id: 15, name: "Shruthi", ...>

如果您只想要當前用戶的關聯並且已經正確設置了“ has_many”,則可以...

current_user.associations.order(created_at: :desc)

這將為您提供所有關聯記錄,(當然)當前用戶信息(例如idname可直接從當前用戶獲得。

這將是一個ActiveRecord :: Relation,您可以對其進行迭代,因此,是的,它的行為就像一個數組。 如果需要所有列表,則需要一個數組或類似數組的結構。

您有兩個選擇。

  1. .first添加到查詢中。

  2. 使用User.find(current_user.id)...

您還需要列表,然后必須遍歷數組

users = User.where("id = #{current_user.id}").include_associations.order(created_at: :desc)
users.each do |user|
  #user is activerecord data here
end

這是您的替代選擇,例如-

 user_array = User.where("id = #{current_user.id}").include_associations.order(created_at: :desc)
active_record_of_users = User.where(id: user_array.map(&:id))

暫無
暫無

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

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