views:

74

answers:

3

Hello I've set up a One-to-Many Association between "orders" and "users". I'm wondering how to have console just return an array containing ID's rather than a full array of data:

user = User.find_by_login("Lesa")

user.orders => [#, #]

user.orders.id

NoMethodError: undefined method `order' for #<User:0x10351f320>
    from /Users/justinz/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:260:in `method_missing'
    from (irb):10

I also tried user.order.id, and received the same message. What am I doing wrong?

+2  A: 

Extract the ID from each item using map:

user.orders.map(&:id)
Tobias Cohen
I whish Ruby 2.0 would deprecate either map or collect... How about collect just because it has more characters?
Jonas Elfström
@jonas, neither name is all that great really, but at least "map" is familiar from other languages like Haskell and PHP. I'm not aware of "collect" being used anywhere else.
Tobias Cohen
A: 

You can use Symbol to_proc shortcut provided by Rails

user.orders.collect(&:id)

This is shorthand for

user.orders.collect { |o| o.id }
Chandra Patni
I whish Ruby 1.9 would deprecate either map or collect... How about collect just because it has more characters?
Jonas Elfström
+2  A: 

Why not simply use ActiveRecord::Associations::ClassMethod "singular_collection_ids"

user.order_ids
ernd enson