开发者

Ruby Console Help with a One-to-Many Association

开发者 https://www.devze.com 2022-12-15 14:18 出处:网络
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:

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 }
0

精彩评论

暂无评论...
验证码 换一张
取 消