Two models exist in my application: User and Record. The scaffold option was used to generate both models. I am currently working within the partial _form.html.erb
of my User model, where I have written some JavaScript to store information in a variable named value.
An AJAX call was implemented to send this JavaScript variable to my User Controller. Below is the JavaScript code:
var value = $('input#quantity').val();
$.ajax({
url: "/info",
type: "POST",
data: {
value: value
},
complete: function(){
console.log('Congrats');
}
});
In the route configuration file, the routes were set as follows:
resources :user
resrouces :record
post '/info'=>'users#registration'
The User controller contains the following methods:
def registration
@value = params[:value]
render json: 'ok'
end
def create
@user = User.new(user_params)
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(user: @user, value: @value)
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
format.js
end
end
I aim to create a new Record when creating a new User. This Record should have the ID of the created User and the attribute value equal to @value.
Although I know that Record.create(user: @user) creates a new Record with the User's ID, my question is how to pass @value from the registration method and make it accessible in the create method?
I have considered using after_create methods for models, but I prefer not to. It is crucial for me to have the @value variable available in the create method without these methods.
When attempting to route my AJAX call to the create method, I encountered an error 400: bad request.