Spencer K.
Spencer K.

Reputation: 469

Receiving 'Completed 500 Internal Service Error'

I have a Twilio integration, and when I receive a text from a phone number, I want to look up that phone number in the Users table in my database to see if they exist, then do some action.

Here are the parameters I'm seeing in the console which I'm getting from the POST call from Twilio (I removed sensitive or irrelevant ones):

Parameters: {"SmsStatus"=>"received", "Body"=>"Blah blah blah", "From"=>"+15555555555"}

And here is the controller method which is getting hit. After I get the phone number, I am trying to (1) create a user instance, (2) extract any URL I'm receiving in the body of the text, and (3) create a new link entry in the DB.

    def incoming_text
        user = User.where(phone: params[:From])
        if user.present?
            url = URI.extract(params[:Body])
            if url.present?
                @link = Link.new(user_id: user[:id], link: url) #Row 27
                ...
            end
        end
    end

Here is the schema for my users table:

  create_table "users", force: :cascade do |t|
    t.string "phone"
    t.boolean "confirmed"
  end

  create_table "links", force: :cascade do |t|
    t.string "link"
    t.integer "user_id"
    t.index ["user_id"], name: "index_links_on_user_id"
  end

Here are the logs. I have also included a TypeError I am getting for Row 26.

User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."phone" = ?  [["phone", "+15555555555"]]
#<User:0x00007efcedb05400>
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.8ms)

TypeError (no implicit conversion of Symbol into Integer):

app/controllers/users_controller.rb:27:in `incoming_text'

Upvotes: 0

Views: 243

Answers (1)

Ramon Marques
Ramon Marques

Reputation: 3264

UPDATED:

Ok now it's clear.

The problem is you're trying to access [:id] from a collection of Users returned by User.where, it'll be possible only on a single User object.

So you need to change your logic to iterate over that collection:

users = User.where(phone: params[:From])
users.each do |user|
  # then you can access user.id here
end

Or just take the first from that list with .first

user = User.where(phone: params[:From]).first

Upvotes: 1

Related Questions