2013-05-03 40 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。