Question

When a user pulls data from the DB onto the screen which all work great but looks naff because it contains brackets etc as you can see below.

[["100056", "lion bar"]]
[["100055", "milky way"]]
[["100054", "mars bar"]]

this is my controller code

@last_posts = Post.order('created_at DESC').limit(1).pluck(:big_id, :customer)

my view is only this at the moment.

<%= @last_posts %><br>  
<%= @last_posts_but1 %><br>
<%= @last_posts_but2 %><br>
<%= @last_posts_but3 %><br>
<%= @last_posts_but4 %><br>
<%= @last_posts_but5 %><br>
Was it helpful?

Solution

Post.order('created_at DESC').limit(1).pluck(:big_id, :customer).flatten

Will return what you're looking for. flatten gets rid of nested arrays. first also works, but you know that your query will return no more than one record. For edge cases, you won't have to do nil checking after flatten because calling it on an empty array returns an empty array.

Also, the select method will return an array of active record objects that only have the big_id and customer attributes populated, not an array of arrays.

NOTE:. If you're looking to change the limit to anything greater than 1, flatten will not work.

OTHER TIPS

result = [[["100056", "lion bar"]],
         [["100055", "milky way"]],
         [["100054", "mars bar"]]]

puts result.map { |x| x.flatten.join(' ') }
# => 100056 lion bar
# => 100055 milky way
# => 100054 mars bar

To summarize comments above:

As you can you can see, while you are limiting to 1 using limit, you are trying to retrieve big_id and customer. It is simialar to select big_id, customer from posts which returns an array of arrays.

Pluck directly converts database result into an array without constructing active record objects.

You can access the attributes as @last_posts.first which gives ["100056", "lion bar"]

@last_posts.map(:&first) or @last_posts.map{|row| |row0|} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top