質問

I am using the acts_as_taggable_on gem: https://github.com/mbleigh/acts-as-taggable-on

This gem accepts user input for tags as comma separated i.e., Clever, Cool, Joyful

I have a partial: shared/_micropost_form that asks for tags:

<%= form_for(@micropost) do |f| %>
   <%= f.text_field :tag_list, placeholder: "Tags", id: "genre_tag_field" %>
<% end %>

However sometimes users enter the tags with hashtags i.e., #Happy #Drunk or #Stupid, #Drunk

How can I make it so that before a Micropost is created, it checks the entered :tag_list if each word starts with a # and if it does then remove the # and add a , (unless there is a , already) to the end of each word. So When the user enters #Happy #Drunk then the tags automatically save as Happy, Drunk

Micropost Model:

acts_as_ordered_taggable

Micropost Controller:

def create
    @user = User.find(params[:user_id])
    @micropost = @user.microposts.build(params[:micropost])
    if @micropost.save
      flash[:success] = "Posted!"
      redirect_to :back
    else
      flash[:notice] = "Error!"
      redirect_to :back
    end
end

Thanks, appreciate any help. Is this possible without tossing the gem?

役に立ちましたか?

解決

Though not verified in practice, here is a solution.

According to README, you can set the following in initializer to remove special characters in tag name:

ActsAsTaggableOn.force_parameterize = true

It seems acts_as_taggable_on doesn't have an installation command and a default initializer. You can put above setting in any file in /initializers/, and preferred a new file dedicated to this gem.

By setting that, all of your tag name inputs will be processed after saving like

my_string.parameterize

Test

"radical)(cc".parameterize
#=> "radical-cc"

"#Happy".parameterize
#=> "happy"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top