Super Spread Sheet S³

Or little computing tricks and hacks

Rails: When join tables have no class

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:

# \dt;
# 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:

c.article_ids

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:

a.category_ids

returns an array of categories to which the article belongs to.

When in doubt, read the docs:

http://guides.rubyonrails.org/active_record_querying.html

http://guides.rubyonrails.org/active_record_querying.html#joining-tables

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: