2013-03-06 48 views
0

我有一個模型Email_address屬於用戶。而在我的用戶模型中,它表示has_many email_addresses。請看下面的控制檯輸出:Ruby on rails - where子句在關係上產生'undefined method'錯誤


irb(main):073:0>b = EmailAddress.find(2)

EmailAddress Load (0.4ms) SELECT email_addresses.* FROM email_addresses WHERE email_addresses.id = 2 LIMIT 1

=> #EmailAddress id: 2, email: "[email protected]", user_id: 2, created_at: "2013-03-06 02:33:40", updated_at: "2013-03-06 02:33:40"

irb(main):074:0>b.user

User Load (0.1ms) SELECT users.* FROM users WHERE users.id = 2 LIMIT 1

=> #User id: 2, username: "w", created_at: "2013-03-06 02:33:40", updated_at: "2013-03-06 02:33:40"

irb(main):075:0>b = EmailAddress.where(:email => "[email protected]")

EmailAddress Load (0.1ms) SELECT email_addresses.* FROM email_addresses WHERE email_addresses.email = [email protected]

=> #EmailAddress id: 1, email: "[email protected]", user_id: 1, created_at: "2013-03-05 07:26:56", updated_at: "2013-03-05 07:26:56"

irb(main):076:0>b.user

NoMethodError: undefined method user for # from /var/lib/gems/1.8/gems/activerecord-3.2.11/lib/active_record/relation/delegation.rb:45:in `method_missing' from (irb):76


誰能告訴我,爲什麼當我使用where()我無法再找到用戶,但它的作品,當我使用find()方法?這是非常令人困惑的輸出。

+0

'EmailAddress.where(:電子郵件=> 「[email protected]」)'產生一個' ActiveRecord ::關係對象。嘗試將其更改爲EmailAddress.where(:email =>「[email protected]」)。首先' – jvnill 2013-03-06 03:23:13

+0

賓果!謝謝jvnill!這是完美的。 – user985723 2013-03-06 03:26:01

+0

儘量使用「範圍」而不是在控制器中使用「where」,因爲它使代碼更具可讀性/可維護性。在這裏閱讀更多關於範圍http://guides.rubyonrails.org/active_record_querying.html#scopes – sameera207 2013-03-06 03:47:35

回答

2

.where()返回數組(具體爲ActiveRecord::Relation)。要選擇返回的對象,您需要指定哪個對象。在這種情況下,因爲你希望一個對象,你可以這樣做:

b = EmailAddress.where(:email => "[email protected]").first 

OR

b = EmailAddress.where(:email => "[email protected]")[0]