Hooking Up Votes And Topics
Goals
Topics |
---|
id |
title |
description |
Votes |
---|
id |
topic_id |
Steps
Step 1: Teach the Topic model about Votes
class Topic < ApplicationRecord has_many :votes, dependent: :destroy endStep 2: Teach the Vote model about Topics
class Vote < ApplicationRecord belongs_to :topic endStep 3: Play around with Topics and Votes in the Rails console
Terminalrails consoleExpected result:$ rails console Running via Spring preloader in process 1234 Loading development environment (Rails 5.1.2) irb(main):001:0>IRBTopic.countIRBmy_topic = Topic.firstIRBmy_topic.update(title: 'Edited in the console')IRBmy_topic.votes.createIRBmy_topic.votes.countIRBmy_topic.votes.first.destroyModel class / association methods
- Topic.first
- Topic.last
- Topic.all
- Topic.count
- Topic.find_by_id(5)
- Topic.destroy_all
- my_topic.votes.count
- my_topic.votes.create
- my_topic.votes.destroy_all
Model instance methods
- my_topic.title
- my_topic.title = 'New title'
- my_topic.update(title: 'New title')
- my_topic.save
- my_topic.save!
- my_topic.destroy
- my_topic.votes.first.destroy
Explanation
Next Step:
Go on to Allow People To Vote
Back to Voting On Topics