簡體   English   中英

Ruby on Rails-ActiveRecord關系無法識別字段

[英]Ruby on Rails - field not recognized by ActiveRecord relation

我的應用程序有一個User表,其中包含所有用戶的列表。 該表具有一個名為activeBoolean field

我有以下代碼來獲取用戶:

existing_user = User.where("LOWER(email) = ?", auth_hash['info']['email'].downcase)

這就是當我做一個existing_user.inspect user.inspect時得到的:

User Load (1.9ms)  SELECT "users".* FROM "users" WHERE (LOWER(email) = 'biswanath.chandramouli@gmail.com')
#<ActiveRecord::Relation [#<User id: 4, name: "Biswanath Chandramouli", email: "Biswanath.Chandramouli@gmail.com", last_updated_by: "", admin: true, active: true, last_updated_on: nil, created_at: "2018-10-30 08:14:59", updated_at: "2018-10-30 08:14:59"

如您所見,如上所述, existing_useractive屬性active可用active

但是此代碼失敗:

if(!existing_user.active?)

上面的調用拋出此錯誤:

undefined method `active?' for #<User::ActiveRecord_Relation:0x00007f0a58b2c500> Did you mean? acts_like?

existing_user.inspect顯示為active: true ,為什么上面的調用existing_user.active失敗? 請幫助!

我認為您應該使用if(!existing_user.first.active?) 這將適合您的情況。 Where子句返回一個數組,而不是對象。 在您的情況下, existing_user是一個數組,而不是一個對象。

這個答案是題外話,但可以為您節省很多:

每次您調用這個existing_user = User.where("LOWER(email) = ?", auth_hash['info']['email'].downcase) ,它將對表中的所有電子郵件進行小寫並尋找正確的一。

我建議在保存用戶之前對電子郵件進行小寫,並在其上添加索引

before_save { self.email = self.email.downcase }

然后獲取用戶:

user = User.where(email: auth_hash['info']['email'].downcase).first

嘗試這種方法,您會發現數據檢索有很大的不同(現在是1.9ms

暫無
暫無

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

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