如何使用twilio&rails在SMS中显示单独的订单?

如何使用twilio&rails在SMS中显示单独的订单?

问题描述:

我有一个食品订购网站应用程序,直接发送食品订单到我的送货司机。我想显示订购的每餐的清单以及数量。我无法在SMS表单中正确显示此内容。如何使用twilio&rails在SMS中显示单独的订单?

在我的应用程序中,用户可以选择餐食,然后将其作为cart_item添加到购物车中。一旦用户支付购物车,就会产生费用。

下面是代码:

charges_controller.rb

def create 
    @charge = Charge.new(charge_params) 

    @amount = @cart.total_price 
    @phone = @charge.phone 
    @location = @charge.address 
    @meal_order = @cart.meal_order 

    begin 
    customer = Stripe::Customer.create(
     :email => @charge.email, 
     :card => params[:stripeToken] 
    ) 

    charge = Stripe::Charge.create(
     :customer => customer.id, 
     :amount  => @amount, 
     :description => 'Rails Stripe Customer', 
     :currency => 'usd' 
    ) 

    # TWILIO 
    send_text_message(@phone, @meal_order, @location, @amount) 

    rescue Stripe::CardError => e 
    flash[:error] = e.message 
    redirect_to charges_path 
    end 

    @cart.destroy 

    respond_to do |format| 
    if @charge.save 
     format.html { redirect_to root_path, notice: 'Charge was successfully created.' } 
     format.json { render :show, status: :created, location: @charge } 
    else 
     format.html { render :new } 
     format.json { render json: @charge.errors, status: :unprocessable_entity } 
    end 
    end 
end 

def send_text_message(customer_phone, meal_order, location, amount) 
    number_to_send_to = "xxx-xxx-xxx" 

    account_sid =   ENV["account_sid"] 
    auth_token =   ENV["auth_token"] 
    twilio_phone_number = ENV["twilio_phone_number"] 

    @client = Twilio::REST::Client.new account_sid, auth_token 

    @client.account.messages.create(
    :from => "#{twilio_phone_number}", 
    :to => number_to_send_to, 
    :body => "New meal order! 
       Customer Phone number: #{customer_phone}. 
       Meal Order: #{meal_order}.  
       Location: #{location}  
       Total: $#{amount/100}"  
) 
end 

cart.rb

def meal_order 
    cart_items.to_a do |item| 
    item.meal.name 
    item.quantity 
    end 
end 

一个例子短信回应,我得到的将是这样的:

新餐订购!
客户电话号码:xxx-xxx-xxxx
用餐顺序: CartItemid:26,meal_id:6,cart_id:16,created_at:“2014-12-06 12:03:11”,updated_at:“2013-12 -06 12:04:11“,数量:2, CartItemid:27,meal_id:3,cart_id:16,created_at:”2014-12-06 12:03:11“,updated_at:”2013-12-06 12 :04:11" ,数量:3 地点:6200客户街圣地亚哥,加州
总计:$ 45

我宁愿为它整齐地打印出饭菜的名称以及数量而不是像现在这样打印出来。有任何想法吗?

你在那里看起来很不错。我认为问题在于你的Cart#meal_order方法没有达到你所期望的。我不确定当to_a通过时,它会对块做任何事情。所以meal_order只是返回cart_items,它打印时,正在输出cart_items的属性。

尝试这样代替:

def meal_order 
    item_names = cart_items.map do |item| 
    "#{item.meal.name} - #{item.quantity}" 
    end 
    item_names.to_sentence 
end 

通过这种方式,我们用地图打开车中的物品到包含名称和数量的字符串。由于您使用的是Rails,因此您可以在数组上使用to_sentence将数组转换为以逗号分隔的句子,最后两个元素用“和”分隔。

让我知道这是否有帮助!

+0

你先生真棒!这就是为什么我在Rails之前就应该关注Ruby。谢谢! :) – 2014-12-07 13:52:06

+0

没问题!与其他应用程序祝好运。 – philnash 2014-12-07 13:55:56