I have two models : User and Record. I used scaffold option to generate both my models. I am working in the partial _form.html.erb
of my User model and I wrote some javascript to store some piece of information into a javascript variable named value.
Then I implemented an AJAX call to send the javascript variable to my User Controller. Here is my javascript code :
var value = $('input#quantity').val();
$.ajax({
url: "/info",
type: "POST",
data: {
value: value
},
complete: function(){
console.log('Congrats');
}
});
Then in my config route file
I wrote the route like this :
resources :user
resrouces :record
post '/info'=>'users#registration'
And in my User controller I have 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
What I would like to do is to create a new Record when creating a new User. This record would have the id of the created User and the attribute value would be equal to @value.
I know and I tried it before that Record.create(user: @user) creates a new Record with the id of the User. It is ok for this part.
My question is how to pass @value from the registration method and to make it available in the create method ?
I've read a lot about models and to write after_create methods....but I don't want to use them. I really need to have the @value variable available in my create method.
I tried to route my AJAX call to the create method but then I have the error 400 : bad request