Hooking Up Votes And Topics
Goals
Topics |
---|
id |
title |
description |
Votes |
---|
id |
topic_id |
Pasos
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
Next, open a Rails console in a terminal window:rails cExpected result:$ rails c Loading development environment (Rails 5.0.0) 2.3.0 :001 >See how many topics exist:Topic.countSave the first topic into a variable:my_topic = Topic.firstChange the title of that topic to something else:my_topic.update_attributes(title: 'Edited in the console')Add a vote to that topic:my_topic.votes.createSee how many votes that topic has:my_topic.votes.countRemove a vote from that topic:my_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_attributes(title: 'New title')
- my_topic.save
- my_topic.save!
- my_topic.destroy
- my_topic.votes.first.destroy
Explicación
Next Step:
Go on to Allow People To Vote
Back to Running Your Application Locally