如何将数据从ajax()传递到控制器Rails

时间:2019-01-05 23:35:13

标签: ruby-on-rails ajax

我正在尝试将数据从ajax传递到控制器以更新用户位置,但是getData变量返回nil。我不确定这是否是最好的方法,但是我发现了许多建议使用ajax的解决方案。

预先感谢

//order_controller
def new
@order = Order.new
@cart = @current_cart
end

def create
#  raise 'ss'
getData = params[:data_value]
@location = Geocoder.search(getData)[0]
# console
current_user.latitude = @location.latitude
current_user.longitude = @location.longitude
current_user.address = @location.address
current_user.save

order = current_user.orders.new(status: "pending")
order.item_ids = @current_cart.item_ids
order.save
@current_cart.destroy

redirect_to root_path
end


//new.html.erb
$("#buy").on('click', function(){
//  debugger;
$.ajax({
url : "/orders/",
type : "post",
data : { data_value: 'Paris' },
success: function(post){ alert('WORK') },
error: function(post){ alert('ERROR') }
});
})
<%= button_to "buy" ,  orders_path(@order) , { action: "post", id: 
"buy" }  %>


//routes.rb
post "/orders/:id", to: "orders#create"
resources :orders 
root "sellers#index" 

1 个答案:

答案 0 :(得分:0)

您在发送authenticity_token时错过了提交post ajax request

所有post请求都需要传递authenticity_token作为post请求参数之一。


在此处详细了解authenticity_token

Understanding the Rails Authenticity Token