Rails delegate update invocation

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 = ' some@ema.il ' u.save #=> both User and Profile are saved u.name = 'bar' u.save #=> true, but changes in Profile were not saved! u.email = ' new@ema.il ' u.save #=> true, new User email was saved, Profile - still not! u.name #=> 'bar', but in database it 'foo' 

Why is the profile not updated (saved only for the first time)? How to fix it?

+7
source share
2 answers

ArcaneRain, you should add the option "autosave" in your relationship instead of adding a callback for this:

has_one :profile, :autosave => true

You should also explore the "dependent" options. More details here: http://guides.rubyonrails.org/association_basics.html#has_one-association-reference

+10
source

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 a default scope to always load profile along user if you often use both models.

+1
source

All Articles