johnnygoodman
johnnygoodman

Reputation: 475

Rails Active Record ID vs. Object ID + Active::Relation

I've been receiving messages like this:

warning: Object#id will be deprecated; use Object#object_id

I read and attempted the tricks from Ruby Object#id warnings and Active Record without success:

108-125-94-123:toptickets johnnygoodman$ rails c
Loading development environment (Rails 3.0.3)
>> ticket_id = 8899
=> 8899
>> ticket = Ticket.where(:number => ticket_id)
=> [#<Ticket id: 97, name: "Set Up API to Feed Customer Info into Bronto  ", number: "8899", category_id: 15, created_at: "2011-01-31 21:24:29", updated_at: "2011-01-31 21:24:29", position: 20>]
>> ticket.id
(irb):3: warning: Object#id will be deprecated; use Object#object_id
=> 2175680980
>> ticket[:id]
TypeError: Symbol as array index
        from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/relation.rb:363:in `[]'
        from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/relation.rb:363:in `send'
        from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/relation.rb:363:in `method_missing'
        from (irb):4
>> ticket.class
=> ActiveRecord::Relation

I'd expect that when I queried for ticket it would be of class ActiveRecord::Base. I'm not sure what to do to get that going or if its the direction I should head in.

Goal: Query for a ticket, print its id. In the example above, the id's value should be 97.

Upvotes: 3

Views: 3172

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

ticket = Ticket.where(:number => ticket_id) returns an ActiveRecord::Relation (which when evaluated in IRB, performs the database query and returns an array of tickets). So ticket.id is trying to perform .id on the entire array of tickets, not one actual ticket.

Maybe you only want the first result?

>> ticket = Ticket.where(:number => ticket_id).first
>> puts ticket.id
=> 97

Upvotes: 7

Related Questions