Adding a string in front of a parameter for a form

前端 未结 2 1369
南方客
南方客 2021-01-25 22:06

I want to add a string in front of a paramemter on my form so that when the user submits something on the form, it posts to an external API and my client can log in to freshdesk

相关标签:
2条回答
  • 2021-01-25 22:17

    Your view should have straightforward fields with no magic. We'll use the Form class to do the complicated stuff.

    = f.text_field :subject
    

    The method call to post_tickets does not need to receive the params because the Form object has already been initialized with the params values. Also, you shouldn't post the ticket, I think, unless the object is valid, right?

    def create
      @contacts = Form.new(params[:contacts])
      if @contacts.valid?
        @contacts.post_tickets
        flash[:success] = "Message sent! Thank you for contacting us."
        redirect_to new_contact_path
      else
        flash[:alert] = "Please fill in the required fields"
        render action: 'new'
      end
    end
    

    Your Form model should be responsible for modifying the :subject parameter to include the prefix:

    class Form
      # Some code omitted
    
      def initialize(attributes = {})
        attributes.each do |name, value|
          send("#{name}=", value)
        end
      end
    
      def post_tickets
        client.post_tickets({
          :whatever_fields => whatever_attribute, 
          :username => username, 
          :subject => "Hello from, #{subject}", 
          :email => email, 
          :description => description
        })
      end
    
    end
    

    That way, the Form object has the correct values as submitted by the user, but you've overwritten the posted subject so that it will return the combined string you want, with "Hello from..."

    In post_tickets, reference directly the parameters you want to send, via the attributes with which the Form object has been initialized. In the case of subject, you'll send a combined value instead.

    Please note, I've rewritten your initialize to use a more classic attribute setting method.

    Thoughts, questions?

    0 讨论(0)
  • 2021-01-25 22:36

    You should do this in your model by adding your substring before the value que form will send you. This seems business logic, it shouldn't be in the view.

    def post_tickets(params)
       client.username = "Hello From, " + client.username
       client.post_tickets(params)
    end
    
    0 讨论(0)
提交回复
热议问题