2013-05-03 89 views
0

我有以下WHERE語句:Rails Model.where如何獲得ID?

 <% location = Location.where('locname' == client.locname) %> 

如何獲得位置記錄的.ID,它發現了什麼?

這不起作用:

 <% location = Location.where('locname' == client.locname).id %> 

感謝您的幫助!

+1

這甚至不是有效的語法... – sevenseacat 2013-05-03 14:45:43

回答

1
<% location = Location.where("locname = ?", client.locname).first.id %> 

的原因是where將返回ActiveRecord::Relation,因此您可以遍歷元素或只是抓住第一個就像我上面一樣。

+0

感謝 - 工作 - 我會接受時限到了。 – Reddirt 2013-05-03 14:42:39

+0

沒問題@Reddirt,確保你有正確的語法。 – 2013-05-03 15:00:20

0

您也可以通過使用類似的ActiveRecord提供的查找方法:

<% location = Location.find(:first, :conditions => ["locname = ?", client.locname]).id %> 

也知道,您需要正確paramterize您的查詢,以消除SQL注入的所有可能性。

0

你之所以提供您的第一個代碼示例不會讓你獲得的ID,是不是位置類的一個實例。從我自己的項目使用一些代碼:

1.9.2p290 :001 > ch = Character.where(name: 'Catharz') 
Character Load (2.9ms) SELECT "characters".* FROM "characters" WHERE "characters"."name" = 'Catharz' 
=> [#<Character id: 2, name: "Catharz", player_id: 2, archetype_id: 4, created_at: "2012-03-29 07:10:31", updated_at: "2012-11-26 05:36:11", char_type: "m", instances_count: 348, raids_count: 148, armour_rate: 5.1, jewellery_rate: 5.29, weapon_rate: 5.48>] 

1.9.2p290 :002 > ch.class 
=> ActiveRecord::Relation 

這是因爲返回ActiveRecord:Relation類模仿你的類的實例。你可以通過在返回的值上調用#klass來看到這一點。

1.9.2p290 :002 > ch.klass 
=> Character(id: integer, name: string, player_id: integer, archetype_id: integer, created_at: datetime, updated_at: datetime, char_type: string, instances_count: integer, raids_count: integer, armour_rate: float, jewellery_rate: float, weapon_rate: float) 

但是,如果你嘗試並獲得一個ID,你會得到以下異常:

1.9.2p290 :004 > ch.id 
NoMethodError: undefined method `id' for #<ActiveRecord::Relation:0xce58344> 

ActiveRecord的::關係類,可以鏈接在一起範圍,不執行SQL,直到你需要它被執行。這就是爲什麼路易斯上面的答案會奏效。在ActiveRecord :: Relation上調用#first將強制查詢被執行。

由於設計上的指針,你應該在你的控制器,然後使用實例變量在您的視圖指定自己的位置作爲@location。