Как передать данные из ajax () в контроллер Rails - PullRequest
0 голосов
/ 06 января 2019

Я пытаюсь передать данные из 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 голосов
/ 06 января 2019

Вы пропускаете отправку authenticity_token при отправке post ajax request

Все post запросы требуют передачи authenticity_token в качестве одного из post параметров запроса.


Подробнее о authenticity_token здесь

Понимание токена подлинности Rails

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...