userstable: |id|name|password|
userdetailstable: |id|col1|col2|col3|user_id|
this is my code:
def create
@user = User.new(@params['user'])
@userdetail = Userdetail.new(@params['userdetail'])
if @user.save and @userdetail.save
flash[:notice] = "Save succeeded..."
redirect_to :action => 'list'
else
flash[:notice] = "Save FAILED"
render_action 'new'
end
end
I want to put the auto_incremented id of the first table(userstable)
into the user_id field of the second(userdetails) table
or is there a better way to do a multiple insert and at the same time
create a relationship
thanx tim
You should simply be able to do:
@user = User.new params[:user]
@user_detail = UserDetail.new params[:userdetail]
@user.userdetail = @user_detail
@user.save
And that should do it. Rails should take care of the rest. This should
also work on has_many relationships and such as well.
-Nick
Tim van Oostrom wrote:
if @user.save and @userdetail.save
into the user_id field of the second(userdetails) table
or is there a better way to do a multiple insert and at the same time
create a relationship
class User < ActiveRecord::Base
has_one :details, :class_name => ‘UserDetail’
validates_associated :details
end
class UserDetail < ActiveRecord::Base
belongs_to :user
end
@user = User.new( params[‘user’] )
@user.details = Userdetail.new( params[‘userdetail’] )
if @user.save
…
–
We develop, watch us RoR, in numbers too big to ignore.
From the documentation:
Peak Obsession.
html#M000472
@user = User.new( params[‘user’] )
@user.create_details( params[‘userdetail’] )
if @user.save
…
Tom F. wrote:
From the documentation:
Peak Obsession.
html#M000472
@user = User.new( params[‘user’] )
@user.create_details( params[‘userdetail’] )
if @user.save
…
Ah it works now…
this line had to be:
@user.create_details( params[‘userdetail’] )
Tom F. wrote:
@user.create_details( params[‘userdetail’] )
Yes, that is more concise than
@user.details = Userdetail.new( params[‘userdetail’] )
–
We develop, watch us RoR, in numbers too big to ignore.
I tried your solutions in various versions but i cant get it to work.
I did fix it myself but somehow i think it can be easier.
mycode:
@user = User.new(params[:user])
@user.save
@userdetail = Userdetail.new(params[:userdetail])
@userdetail.user_id = @user.id
if @userdetail.save
…
Ok, maybe i dont understand it correct but here is how i think it is.
when i see this:
class User < ActiveRecord::Base
has_one :userdetail
end
class Userdetail < ActiveRecord::Base
belongs_to :user
end
Does that mean that when i initiate a new object:
@user = User.new()
The activerecord autmagically joins the user + userdetails objects together in one object called:
@user?
and should that object also know the foreign key of user_details = user_id when
userstable: |id|name|password|
userdetailstable: |id|col1|col2|col3|user_id|
(where user_id is the foreign key of the id field on the userstable)
fuck…
i meant: > @user.create_userdetail( params[‘userdetail’] )