Reputation: 710
In Ruby on Rails, I am trying to fetch value from user_id and id column in rails. Now I am using the following code which concatenate two columns firstname and lastname
@profiles = Profile.all.map{|p| "#{p.users_firstname} #{p.users_lastname}"}
Instead I have to add the columns as two entries. Please help. Thanks in advance
Update
I want to get the values like this
@profile = ['user1_firstname', 'user1_lastname','user2_firstname', 'user2_lastname',....]
Upvotes: 1
Views: 937
Reputation: 6603
Your current code will yield something like:
@profiles = [ 'Edie Pineo', 'Tierra Cardiel', 'Sparkle Berrey' ]
You're asking:
Instead I have to add the columns as two entries
So, if I get it correctly you want instead something like:
@profiles = [ ['Edie', 'Pineo'], ['Tierra', 'Cardiel'], ['Sparkle', 'Berrey'] ]
... which is an Array of Array of Strings as opposed to your current code which is an Array of Strings.
If this is so, the following is a solution:
@profiles = Profile.all.map{|p| [p.users_firstname, p.users_lastname] }
@profiles = Profile.pluck(:users_firstname, :users_lastname).uniq
@profiles = Profile.pluck(:users_firstname, :users_lastname).map{|array| array.map(&:strip) }.uniq
# if you want string values
@profiles = Profile.pluck(:users_firstname, :users_lastname).map{|array| array.map(&:to_s) }.uniq
# if you want integer values
@profiles = Profile.pluck(:users_firstname, :users_lastname).map{|array| array.map(&:to_i) }.uniq
...continuing from our discussion and to answer your Update question
@profiles = Profile.pluck(:users_firstname, :users_lastname).flatten
- tested working
Upvotes: 1
Reputation: 2927
I think you want to use pluck. Below will return an array of arrays with each nested array containing the firstname and the lastname.
Profile.pluck(:users_firstname, :users_lastname)
If, as the title of your question reads, you want a hash, you can convert it to a hash with to_h
. It's not clear from your question how you want the hash to be formatted
Upvotes: 1
Reputation: 2345
Assuming users_firstname
and users_lastname
are attributes of Profile
, you can skip map altogether:
Profile.all.pluck(:user_firstname, :users_lastname)
Upvotes: 1
Reputation: 1638
Is this what you are looking for?
@profiles = Profile.all.select(:users_firstname, :users_lastname).to_a
Upvotes: 0