diff --git a/app/controllers/microposts_controller.rb b/app/controllers/microposts_controller.rb index c87e501..f0a2fce 100644 --- a/app/controllers/microposts_controller.rb +++ b/app/controllers/microposts_controller.rb @@ -17,7 +17,7 @@ class MicropostsController < ApplicationController def create micropost = Micropost.new(micropost_params) micropost.user = helpers.current_user - micropost.add_tags(params[:tags]) + micropost.set_tags(params[:tags]) if params[:tags] if micropost.save redirect_to micropost, notice: t(".created") else @@ -30,6 +30,7 @@ class MicropostsController < ApplicationController def edit; end def update + @micropost.set_tags(params[:tags]) if params[:tags] if @micropost.update(micropost_params) redirect_to @micropost, notice: t(".updated") else diff --git a/app/helpers/microposts_helper.rb b/app/helpers/microposts_helper.rb new file mode 100644 index 0000000..87e3631 --- /dev/null +++ b/app/helpers/microposts_helper.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +module MicropostsHelper + def tag_string(micropost) + micropost.tags.map(&:name).join(" ") + end +end diff --git a/app/models/micropost.rb b/app/models/micropost.rb index 4d97031..d255249 100644 --- a/app/models/micropost.rb +++ b/app/models/micropost.rb @@ -11,9 +11,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) + def set_tags(*tag_names) + tag_names.each do |tag_name| + tag = Tag.find_or_create_by(name: tag_name) + tags << tag unless tags.include?(tag) end end end diff --git a/app/views/microposts/_form.html.erb b/app/views/microposts/_form.html.erb index 476dfdf..d3653ea 100644 --- a/app/views/microposts/_form.html.erb +++ b/app/views/microposts/_form.html.erb @@ -3,7 +3,7 @@ <%= f.rich_text_area :content %> - <%= text_field_tag :tags %> + <%= text_field_tag :tags, tag_string(@micropost) %> <%= f.submit button_text %> <% end %> diff --git a/test/models/micropost_test.rb b/test/models/micropost_test.rb index 8235133..40167aa 100644 --- a/test/models/micropost_test.rb +++ b/test/models/micropost_test.rb @@ -21,7 +21,17 @@ class MicropostTest < ActiveSupport::TestCase test "can add tags" do assert_empty @micropost.tags 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