Or little computing tricks and hacks
Rails: When join tables have no class
July 31, 2016Posted by on
I was revisiting an old project of mine, where I had brilliantly created a join table. I had forgotten, though that I did not create a Rails model, because I did not need one. So coming back to the project, I wanted to count the number of rows in that join table in the command line, rails c.
Surprise! I cannot find the the class name, so I cannot access the table directly there…
Instead, I ran psql database_name:
# SELECT * FROM database_name;
to get the list of all the rows in the table.
The join table I created, joins the ids of other two tables: article and category. In was of the models one find the following statement: has_and_belongs_to_many.
To access the information in the table in the rails console, where c is an object of catergory:
which returns an array of the article ids which are associated with that category. The other direction also works. Given a an object of article:
returns an array of categories to which the article belongs to.
When in doubt, read the docs: