简体   繁体   中英

Rails Model.where how do I get ID?

I have the following where statement:

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

How do I get the .id of the location record that it found?

This didn't work:

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

Thanks for the help!

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

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

You may also use the find method provided by ActiveRecord like:

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

be also aware that you need to paramterize your query properly to eliminate all possibilities of SQL injection.

The reason why your first code sample you provided doesn't allow you to obtain the id, is it isn't an instance of the Location class. Using some code from my own project:

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

This is because returns an instance of the ActiveRecord:Relation class which mimics your class. You can see this by calling #klass on the returned value.

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)

But if you try and get an id, you'll get the following exception:

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

The ActiveRecord::Relation class allows you to chain together scopes, without executing the SQL until you need it to be executed. This is why Luis' answer above will work. Calling #first on the ActiveRecord::Relation will force the query to be executed.

As a pointer on design, you should probably be assigning your location as @location in your controller then using the instance variable in your view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM