Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyway to access a join table in Rails Console?

I have two models - Question, Tag.

I would like to do a count on the number of records in my questions_tags join table.

How can I do that from the Rails Console?

like image 875
marcamillion Avatar asked Mar 12 '13 22:03

marcamillion


People also ask

How do I view a Rails database?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db . Both commands will direct you the command line interface and will allow you to use that database query syntax.


1 Answers

Assuming you have no join model (just a join table), you can execute some arbitrary SQL through one of your existing models to get a count:

Question.connection.execute "select count(*) from questions_tags"

This will get you a db-dependent result object. For PostgreSQL, to get an actual integer out of it with:

Question.connection.execute("select count(*) from questions_tags").first["count"].to_i
like image 86
Jim Stewart Avatar answered Oct 07 '22 03:10

Jim Stewart