Search code examples
ruby-on-railsrubyattributesinstance-variables

Cannot iterate through the attributes of an object


I want to access the value of the document_id value in the DocumentUser instance variable and add it to an array. However, while the function ids is defined and I can access the id value with it, there is no function document_ids defined for this class. I could go ahead and define it, but my question is - can I access the document_ids value without doing that, perhaps by somehow using the map function (which confuses me)? I thought I could iterate through the model since it looks like it returns an Array, but no dice. Thanks!

[110] pry(#<#<Class:0x00007f99646b1b60>>)> @current_user.document_users.each { |n| puts n }
#<DocumentUser:0x00007f9957cce118>
=> [#<DocumentUser:0x00007f9957cce118
  id: 382,
  user_id: 26638,
  document_id: 282,
  created_at: Wed, 08 May 2019 15:05:42 CDT -05:00,
  updated_at: Wed, 08 May 2019 15:05:42 CDT -05:00>]

Solution

  • Yes, it would be this:

    @current_user.document_users.map(&:document_id)
    

    which is a shorthand of this:

    @current_user.document_users.map { |document_user| document_user.document_id }
    

    Since it's probably ActiveRecord class, it's even better way to achieve this result, using pluck:

    @current_user.document_users.pluck(:document_id)