Shelby Westman
2006-Jul-25 01:36 UTC
[Rails] save trouble with has_many belongs_to relationship
I have a bit of code in a controller that looks like this: @current_festival.monitor_preferences.each do |pref| if pref.user_id == @me.id pref.preference = params[:monitor_pref] #pref.save end end @current_festival.save_with_validation(false) the Festival class has_many :monitor_preferences the MonitorPreference class belongs_to :festival In the configuration above, the monitor_preference is not saved with the new value from the params[:monitor_pref]. However, if I uncomment pref.save, then it is saved. Why doesn''t the @current_festival.save_with_validation(false) not save the monitor preferences? FYI, the @current_festival.save... IS saving other values in this method correctly, and I have validation set to false because not all required fields are completed at this point. If anyone can tell me why this save is not happening, I would be grateful. Thanks, Shelby -------------- next part -------------- An HTML attachment was scrubbed... URL: http://wrath.rubyonrails.org/pipermail/rails/attachments/20060725/14514260/attachment.html
Mark Reginald James
2006-Jul-25 07:37 UTC
[Rails] Re: save trouble with has_many belongs_to relationship
Shelby Westman wrote:> I have a bit of code in a controller that looks like this: > > @current_festival.monitor_preferences.each do |pref| > if pref.user_id == @me.id <http://me.id> > pref.preference = params[:monitor_pref] > #pref.save > end > end > @current_festival.save_with_validation(false) > > the Festival class has_many :monitor_preferences > the MonitorPreference class belongs_to :festival > > In the configuration above, the monitor_preference is not saved with the > new value from the params[:monitor_pref]. However, if I uncomment > pref.save, then it is saved. > > Why doesn''t the @current_festival.save_with_validation(false) not save > the monitor preferences? FYI, the @current_festival.save... IS saving > other values in this method correctly, and I have validation set to > false because not all required fields are completed at this point.When an Active Record parent model instance is saved you only get automatic saving of has-many-associated child objects/records when either the parent or the child is a new record (i.e not yet saved to the DB). Otherwise you have to save explicitly. Some work has been done to investigate the possibility of automatically saving (updating) existing associated objects if a change in their attributes has been detected. -- We develop, watch us RoR, in numbers too big to ignore.