Tag refinements

- Don’t allow duplicates
- Allow edits correctly
This commit is contained in:
Trevor Vallender 2023-10-19 19:36:08 +01:00
parent 6358e2a61e
commit d5b587499c
5 changed files with 25 additions and 6 deletions

View File

@ -17,7 +17,7 @@ class MicropostsController < ApplicationController
def create def create
micropost = Micropost.new(micropost_params) micropost = Micropost.new(micropost_params)
micropost.user = helpers.current_user micropost.user = helpers.current_user
micropost.add_tags(params[:tags]) micropost.set_tags(params[:tags]) if params[:tags]
if micropost.save if micropost.save
redirect_to micropost, notice: t(".created") redirect_to micropost, notice: t(".created")
else else
@ -30,6 +30,7 @@ class MicropostsController < ApplicationController
def edit; end def edit; end
def update def update
@micropost.set_tags(params[:tags]) if params[:tags]
if @micropost.update(micropost_params) if @micropost.update(micropost_params)
redirect_to @micropost, notice: t(".updated") redirect_to @micropost, notice: t(".updated")
else else

View File

@ -0,0 +1,7 @@
# frozen_string_literal: true
module MicropostsHelper
def tag_string(micropost)
micropost.tags.map(&:name).join(" ")
end
end

View File

@ -11,9 +11,10 @@ class Micropost < ApplicationRecord
has_many :microposts_tags has_many :microposts_tags
has_many :tags, through: :microposts_tags has_many :tags, through: :microposts_tags
def add_tags(*tag_names) def set_tags(*tag_names)
tag_names.each do |tag| tag_names.each do |tag_name|
tags << Tag.find_or_create_by(name: tag) tag = Tag.find_or_create_by(name: tag_name)
tags << tag unless tags.include?(tag)
end end
end end
end end

View File

@ -3,7 +3,7 @@
<%= f.rich_text_area :content %> <%= f.rich_text_area :content %>
<%= text_field_tag :tags %> <%= text_field_tag :tags, tag_string(@micropost) %>
<%= f.submit button_text %> <%= f.submit button_text %>
<% end %> <% end %>

View File

@ -21,7 +21,17 @@ class MicropostTest < ActiveSupport::TestCase
test "can add tags" do test "can add tags" do
assert_empty @micropost.tags assert_empty @micropost.tags
assert_difference "@micropost.tags.count", +3 do assert_difference "@micropost.tags.count", +3 do
@micropost.add_tags("foo", "bar", "baz") @micropost.set_tags("foo", "bar", "baz")
end
end
test "duplicate tags are not added" do
assert_empty @micropost.tags
assert_difference "@micropost.tags.count", +3 do
@micropost.set_tags("foo", "bar", "baz")
end
assert_no_difference "@micropost.tags.count" do
@micropost.set_tags("bar", "baz")
end end
end end
end end