Hi,
I have two models in my application, User and Profile, looking like
this:
class User < ActiveRecord::Base
has_one :profile, :dependent => :destroy
end
class Profile < ActiveRecord::Base
belongs_to :user
end
What I want to do is to be able to edit a user object instance and the
associated profile from the same form. I''ve tried to reference the
profile in my view template as can be seen below (my edit action
instantiates a @user variable with data from the db).
<%= text_area ''user.profile'',
''about_message'', :cols => 20, :rows => 3
%>
However, when I try to load the page in my browser I get an error:
`@user.profile'' is not allowed as an instance variable name
I then choosed to add a @profile variable and reference it instead.
<%= text_area ''profile'', ''about_message'',
:cols => 20, :rows => 3 %>
This works for the view part, but my controller code doesn''t behave as
expected. Here''s what I try to do:
@user.attributes = params[:user]
@user.profile.attributes = params[:profile]
@user.save
I''ve read in AWDWR that Active Record automatically saves dependent
child rows when the parent row is saved (and wraps the inserts/updates
in a transaction), but for some reason I can''t get it to work. Only the
changes to the user object are saved ...
After some googling I decided to use the "update_attributes" method
and
since I make two separate database calls I''ve wrapped them in a
transaction.
begin
transaction do
@user.update_attributes(params[:user])
@profile.update_attributes(params[:profile])
end
rescue
success = false
end
This worked eventually, but intuitively it doesn''t feel like the right
way to solve the problem. What do I need to do to have the profile being
saved automatically when the user is saved? Is it possible at all?
What I would like to be able to do is something like either:
1)
View:
<%= text_area ''user.profile'',
''about_message'', :cols => 20, :rows => 3
%>
Action:
@user.update_attributes(params[:user])
or
2)
View:
<%= text_area ''profile'', ''about_message'',
:cols => 20, :rows => 3 %>
Action:
@user.attributes = params[:user]
@user.profile.attributes = params[:profile]
@user.save
Any help to shed some light on this is much appreciated. Cheers
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---