2

I am new in ruby on rails and I am trying to send the post request using ajax to the controller method but the it throw the exception

ActionController::InvalidAuthenticityToken in DonationsController#create_user_account

I have google it but no idea what to do to solve this.

It is the main controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

Here is the code of donations controller

def create_user_account
    @donation = Donation.find(params[:a])
    @pars = [@donation.a]
    print @pars
    render plain: "OK"
  end

private # Use callbacks to share common setup or constraints between actions. def set_donation @donation = Donation.find(params[:id]) end

def set_campaign
  @campaign = Campaign.find(params[:campaign_id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def donation_params
  params.require(:donation).permit(:amount, :user_id, :campaign_id)
end
coreyward
  • 68,091
  • 16
  • 122
  • 142
john
  • 512
  • 4
  • 24
  • You're not including the CSRF token in the AJAX request –  Apr 15 '17 at 14:12
  • Can you share your view code? – Gerry Apr 15 '17 at 14:25
  • after adding token $.ajax({ beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, type: 'GET', url: "http://localhost:3000/donations/create_user_account", data:{a:'abc'}, dataType: 'json' }).done(function(data) { }); This error occurs ActiveRecord::RecordNotFound in DonationsController#show Couldn't find Donation with 'id'=create_user_account Extracted source (around line #173): The route is post 'donations/create_user_account' => 'donations#create_user_account' – john Apr 15 '17 at 14:32
  • Your are probably not sending the `id` (i.e. your are sending a `null` value). Check your `show` action in your controller, but the problem is likely to be in your view. – Gerry Apr 15 '17 at 14:38
  • I have not defined any view. I am just trying to get values in the controller method. I am sending data using ajax call and why I need to send id ?? I dont want to send id. – john Apr 15 '17 at 14:41
  • You need to send `id` because `find` method uses `id`. If you have a column named `a` just change `@donation = Donation.find(params[:a])` to `@donation = Donation.find_by(a: params[:a])`. – Gerry Apr 15 '17 at 14:47
  • Same error ActiveRecord::RecordNotFound in DonationsController#show Couldn't find Donation with 'id'=create_user_account – john Apr 15 '17 at 14:50
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/141775/discussion-between-john-and-gerry). – john Apr 15 '17 at 14:50
  • Check out this question/answer: http://stackoverflow.com/questions/941594/understanding-the-rails-authenticity-token – Gaston Apr 16 '17 at 17:50

0 Answers0