Step 3: Play around with Topics and Votes in the Rails console
First, make sure you've made at least one topic on the site.
Next, open a Rails console in a terminal window:
$ rails console
Running via Spring preloader in process 1234
Loading development environment (Rails 5.1.2)
To get out of the console, type exit.
At the console, try the following things
See how many topics exist:
Save the first topic into a variable:
my_topic = Topic.first
my_topic here could have been any variable name, but we'll stick with my_topic for consistency.
Change the title of that topic to something else:
my_topic.update(title: 'Edited in the console')
Add a vote to that topic:
See how many votes that topic has:
Remove a vote from that topic:
Note that the things you can do to Model classes (like Topic and Vote), differ from the things you can do to Model instances (like my_topic, here). my_topic.votes is an association, and here behaves mostly like a model class.
In Rails, relationships between models are called associations.
Associations (usually) come in pairs.
A topic will have many votes so we put has_many :votes in the
When you ask a topic for its votes, you get an array of votes
for that topic.
A vote is for a particular topic, so we put belongs_to :topic
in the vote model.
When you ask a vote for its topic, you get the topic for that
It can still be important to clean up after yourself! dependent: :destroy
on has_many :votes means when a Topic gets destroyed, all
the votes that correspond to it will be destroyed, too. Without
dependent: :destroy, those votes would live on the database forever.