使用rails,这个查询有什么问题,它不会返回有效的id

问题描述 投票:-2回答:1

STORE_ID = Store.select(:ID)。凡(USER_ID:current_user.id).to_a.first

它返回如下id:Store:0x00007f8717546c30

ruby-on-rails-5
1个回答
0
投票
Store.select(:id).where(user_id:current_user.id).to_a.first

select不返回给定列的字符串或整数数组,而是包含仅包含给定字段的对象的活动记录关系:

https://apidock.com/rails/ActiveRecord/QueryMethods/select

然后,您的代码将该关系转换为数组,并获取该数组中的第一个对象,该数组是Store类的实例。如果您需要ID,请尝试:

Store.select(:id).where(user_id:current_user.id).to_a.first.id

但是,我认为你误解了如何构建查询。将where部分放在第一位,然后找到第一个结果的ID:

Store.where(user_id: current_user.id).first.id

如果只有一家商店,那么:

Store.find_by(user_id: current_user.id).id

要么...

Store.find_by(user: current_user).id

要么.....

current_user.store.id

(或current_user.stores.first.id,如果有很多)

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