Reddirt
Reddirt

Reputation: 5953

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!

Upvotes: 0

Views: 312

Answers (3)

Catharz
Catharz

Reputation: 1165

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.

Upvotes: 0

jethroo
jethroo

Reputation: 2124

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.

Upvotes: 0

Lu&#237;s Ramalho
Lu&#237;s Ramalho

Reputation: 10198

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

The reason is that where will return an ActiveRecord::Relation, thus you can either loop through the elements or just grab the first one as I did above.

Upvotes: 1

Related Questions