Search code examples
ruby-on-railsformsdefault-value

How to set a default url in a Rails form


In my app users can list someone's instagram profile, but they would have to copy and paste the entire url in the form.

<%= f.url_field :url,required: true,label: "URL (required)" %>

How do i set the default url in my form as instagram.com/ so that they would only need to enter the username?


Solution

  • You can just ask for username and later in controller/form model remove @ (and whole 'http://instagram.com/' prefix if someone pastes url instead of username)

    <%= f.text_field :instagram_username, required: true, label: "instagram.com/" %>
    

    Controller something like:

     obj = Model.new(model_params)
     if (username = params.dig(:some_model, :instagram_username))
       username = username.gsub(%r{https?://instagram.com/}, '').gsub(/^@/, '')
       obj.url = "https://instagram.com/#{CGI.escape username}"
     end