In my current project, I am working with Rails 4 which involves a User model and a Record model. My goal is to pass two javascript variables to the create method of the controller.
To achieve this, I have set up an AJAX call:
var funds = $('input#test').val();
var weight = $('input#result').val();
$.ajax({
url: "/final",
type: "POST",
data: {
funds: funds,
weight: weight,
},
complete: function(){
console.log('Congrats');
}
});
I have defined the route in my config file like so:
post '/register' => 'users#create'
Here is the corresponding controller code:
def create
@user = User.new(ticket_params)
@funds = params([:funds])
@weight = params([:weight])
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
Record.create(fund: @funds, weight: @weight)
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
format.js
end
end
However, I encountered a 400 bad request error.
I want to ensure that the variables funds
and weight
are passed correctly to the create method of the controller for further use.
After some investigation, I found out that changing the AJAX call verb from POST to GET resolves the error message. But then, when creating the User, the controller claims that the parameters are empty, even though I verified them.
How can I effectively send javascript variables to the create method?
Below is the error message recorded in the network console of my browser:
ActionController::ParameterMissing in UsersController#create
param is missing or the value is empty: user
Application Trace
app/controllers/users_controller.rb:109:in `user_params'
app/controllers/users_controller.rb:40:in `create'
The error displayed in the console is as follows:
POST http://localhost:3000/final 400 (Bad Request)
m.ajaxTransport.send @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:6
m.extend.ajax @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:6
(anonymous function) @ VM2175:27
m.event.dispatch @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:5
m.event.add.r.handle @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:5