I have two models ; User and Record. I would like to create automatically a new Record when creating a new User. The new Record must have an attribute which is the id of the newly created User.
I have read about using link_to, to pass a parameter but I deem this is not what I need. I'd like the code to be in the User Controller in the create action.
So I wrote this code in my controller :
def create
@user = User.new(user_params)
@record = Record.new(:user_id=>@user.id)
@record.save
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 }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
format.js
end
end
To check if it could work I wrote this instead of what is in the previous code. And it works I have a new record with an id for the user of 1
@Record = Record.new(:user_id=>"1")
@Record.save
How can I get instead of 1 the id of the User that is created ?
I tried several options :
params[:id]
User.find(params[:id])