Artsom
Artsom

Reputation: 171

Print attribute of object

I have 2 classes with:

class User < ApplicationRecord
  has_one :address
end

class Address < ApplicationRecord
  belongs_to :user

I need to write code, which will print the value of attribute with the name 'postcode' of 100 users from database.

I have some code on this point, but not sure that it's a good way to solve the problem:

@users = User.all
@users.limit(100).each do |user|
  puts "#{user.postcode}" 
end

Who has better ideas?

Upvotes: 2

Views: 63

Answers (2)

mrzasa
mrzasa

Reputation: 23307

I'd use pluck

puts User.limit(100).pluck('postcode')
# or
puts User.joins(:address).limit(100).pluck('addresses.postcode')

Upvotes: 3

Rakesh
Rakesh

Reputation: 841

Pluck is best suited for your scenario.

User.where(condition).pluck(:postcode)

(#where condition is optional)

Event if you want to fetch other column with postcode you can simply include that in pluck. for e.g.

User.where(condition).pluck(:id, :postcode)

(#using multiple column inside pluck will only work with rails4 and above)

Upvotes: 0

Related Questions