Home > Software engineering >  How to interpolate username in POST request Rails
How to interpolate username in POST request Rails

Time:07-06

I'm making a POST request in my Registrations Controller:

request.body = "{\"tags\":[\"registroweb\"],\"CustomId\":\"1\",\"name\":\"#{@user.name}\",\"email\":\"email\"}"

I can't make the user.name interpolate correctly, I've tried #{@user.name} with no luck.

¿How can this be achieved?

Thanks!

#registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  require 'uri'
require 'net/http'
require 'openssl'


  def new
    @email = params[:email]
    build_resource
    yield resource if block_given?
    respond_with resource
  end

  def create
    super
    if @user.save
        #Tell the UserMailer to send a welcome email after save
        UserMailer.with(user: @user).welcome_email.deliver_now
        UserMailer.with(user: @user).notify_admins_email.deliver_now
        require 'uri'
        require 'net/http'
        require 'openssl'

        url = URI("https://xxx.xx/api/invoicing/v1/contacts")

        http = Net::HTTP.new(url.host, url.port)
        http.use_ssl = true

        request = Net::HTTP::Post.new(url)
        request["Accept"] = 'application/json'
        request["Content-Type"] = 'application/json'
        request["key"] = 'xxx'
        request.body = "{\"tags\":[\"registroweb\"],\"CustomId\":\"1\",\"name\":#{@user.name},\"email\":\"email\"}"

        response = http.request(request)
        puts response.read_body
    end
  end

end

CodePudding user response:

It's hard to decode the request.body in json format so i suggest you to do it like this and i hope this will help you debug the problem.

body = {
  tags: ['registroweb'],
  CustomId: '1',
  name: @user.name,
  email: 'email'
}
request.body = body.to_json
  • Related