0

我有以下 where 语句:

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

如何获取它找到的位置记录的 .id?

这没有用:

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

谢谢您的帮助!

4

3 回答 3

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

原因是它where会返回一个ActiveRecord::Relation,因此您可以循环遍历元素,也可以像上面那样抓取第一个元素。

于 2013-05-03T14:38:31.570 回答
0

你也可以使用 ActiveRecord 提供的 find 方法,比如:

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

另请注意,您需要正确参数化查询以消除 SQL 注入的所有可能性。

于 2013-05-03T15:16:51.513 回答
0

您提供的第一个代码示例不允许您获取 id 的原因是它不是 Location 类的实例。使用我自己项目中的一些代码:

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::Relation 类允许您将范围链接在一起,而无需执行 SQL,直到您需要执行它。这就是为什么 Luis 上面的回答会起作用的原因。在 ActiveRecord::Relation 上调用 #first 将强制执行查询。

作为设计指针,您可能应该在控制器中将您的位置分配为@location,然后在视图中使用实例变量。

于 2013-05-03T15:25:05.757 回答