Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails delegate update call

I have two models:
User (email:string)
Profile (name:string)

class User < ActiveRecord::Base
   has_one :profile   
   delegate :name, :name=, :to => :profile   
end
class Profile < ActiveRecord::Base
  belongs_to :user
end

rails c

u = User.new 
u.build_profile         #=> init Profile
u.name = 'foo'
u.email = '[email protected]'
u.save                  #=> both User and Profile are saved

u.name = 'bar'
u.save                  #=> true, but changes in Profile were not saved!

u.email = '[email protected]'
u.save                  #=> true, new User email was saved, Profile - still not!

u.name                  #=> 'bar', but in database it's 'foo' 

Why the Profile is not being updated(saved only for the first time)? How to fix this?

like image 900
Rustam A. Gasanov Avatar asked Feb 10 '12 13:02

Rustam A. Gasanov


2 Answers

ArcaneRain, you should add the 'autosave' option on your relationship instead of adding a callback for that:

has_one :profile, :autosave => true

you should also investigate the 'dependent' options. More info here: http://guides.rubyonrails.org/association_basics.html#has_one-association-reference

like image 147
gamov Avatar answered Nov 17 '22 01:11

gamov


This question looks familiar :)

Just tried this and it works:

after_save :save_profile, :if => lambda {|u| u.profile }

def save_profile
  self.profile.save
end

Sidenote:

I advise you to add some default scope to always load the profile along the user if you often use both models.

like image 39
apneadiving Avatar answered Nov 17 '22 01:11

apneadiving