Home In Rails console, how do I show all sql selected attributes?
Reply: 3

In Rails console, how do I show all sql selected attributes?

Abram
1#
Abram Published in 2017-12-30 18:07:50Z

This has been a confusing issue for me for years, and I've never asked about it. Why is it that I can't see name in the following console output even though I clearly selected it?

If I assign that output to a variable and say relation.first.name I will see the name, but I can't get the name to show in console. Also, if I convert the ActiveRecord relation to an array, I see a similar problem:

2.3.5 :070 > a.first
#<ActsAsTaggableOn::Tagging:0x00007ff9f3779aa8> {
    :id => 139
}
2.3.5 :071 > a.first.name
"phones"

Is there a better way to deal with this? For the moment, all I can figure is to map this to make it visible, which make writing queries a pain:

a.map{|tag| [tag.id, tag.name]}

Aleksandar Misich
2#
Aleksandar Misich Reply to 2017-12-30 18:21:26Z

a.first.attributes

You can also use .attributes['column_name'] to extract the desired information without relying on dot syntax, which can provide unexpected results.

Derek Hopper
3#
Derek Hopper Reply to 2017-12-30 18:31:21Z

Since you're using ActsAsTaggableOn::Tagging to do your query, the console is only showing attributes it knows about on ActsAsTaggableOn::Tagging. I'm guessing that model doesn't have a name attribute, so it doesn't know to show it.

I believe the results of the query are also a bit confusing. The query shows ActsAsTaggableOn::Tagging but I think it's showing the id for the tag.

Since you're trying to query for tags, I would maybe switch your query around if it's an option. I'm a little unclear on what you're trying to achieve, so I'm making an assumption. For example, here's what I would try:

Tag.joins(:taggings).where(:"taggings.context" => "topics")

By doing the join this way, you'll still have access to all of the taggings you're looking for; however, you'll get all of the tag attributes displayed as you want.

Phlip
4#
Phlip Reply to 2017-12-30 19:18:37Z

use .pluck() instead of .select(). Then you don't have intermediate objects who don't know about the name column.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304634 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO