TAGS :Viewed: 4 - Published at: a few seconds ago

[ Rails: Saving Input whithout Spaces ]

I'm searching on how to Save my Input without the spaces.

I collect the input on my form via

<%= f.input :name %>

and use it also for linking

localhost:3000/users/:name

The Problem is, if someone uses Spaces in his name the link is getting all ugly with % signs etc.

How can i store the input without spaces ?

E.g.

input is: Hey im John saving as: HeyimJohn

My Model:

class Show < ActiveRecord::Base

    belongs_to :user

    validates :name, :presence => true, :uniqueness => true

    # Show Cover
    has_attached_file :cover, styles: { show_cover: "870x150#"}
    validates_attachment :cover,
                                             content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png'] },
                                             size: { less_than: 5.megabytes }


    def to_param
        name
    end

end

Answer 1


Using gsub:

> "Hey im John".gsub(/\s+/,"")
 => "HeyimJohn"

And to update a hash, you could do:

params_hash.each { |k, v| params_hash[k] = v.gsub(/\s+/, "") 

Update:

To update a specific attribute in your model, you could define a setter in the model which removes all the white spaces:

def my_attribute=(value)
  write_attribute(:my_attribute, value.gsub(/\s+/,""))
end