From ad03410a65cc88669093c4bbb93d21d4cd532ca5 Mon Sep 17 00:00:00 2001 From: Trevor Vallender Date: Thu, 19 Oct 2023 18:46:41 +0100 Subject: [PATCH] Method to add tags to microposts --- app/models/micropost.rb | 6 ++++++ test/models/micropost_test.rb | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/app/models/micropost.rb b/app/models/micropost.rb index e783493..4d97031 100644 --- a/app/models/micropost.rb +++ b/app/models/micropost.rb @@ -10,4 +10,10 @@ class Micropost < ApplicationRecord has_many :microposts_tags has_many :tags, through: :microposts_tags + + def add_tags(*tag_names) + tag_names.each do |tag| + tags << Tag.find_or_create_by(name: tag) + end + end end diff --git a/test/models/micropost_test.rb b/test/models/micropost_test.rb index 2fd9540..8235133 100644 --- a/test/models/micropost_test.rb +++ b/test/models/micropost_test.rb @@ -17,4 +17,11 @@ class MicropostTest < ActiveSupport::TestCase @micropost.content = nil assert_not @micropost.valid? end + + test "can add tags" do + assert_empty @micropost.tags + assert_difference "@micropost.tags.count", +3 do + @micropost.add_tags("foo", "bar", "baz") + end + end end