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?
Extract the ID from each item using map:
user.orders.map(&:id)
Why not simply use ActiveRecord::Associations::ClassMethod "singular_collection_ids"
user.order_ids
You can use Symbol to_proc
shortcut provided by Rails
user.orders.collect(&:id)
This is shorthand for
user.orders.collect { |o| o.id }
精彩评论