Reputation: 1209
I see that ActiveRecord has an autosave method for saving associated models when the parent model's 'save' is called. Is there any way to autosave the whole model? In other words can I give the model some kind of declaration and not bother with a 'commit to database step'?
Right now I have to say:
@household.address = "new address"
@household.save
But I'd rather say:
@household.address = "new address"
and be done.
If the above question doesn't make sense to you, let me give you some context!
In my Schema I have a lots and lots of has_many throughs. I love that whenever I update one piece of my model the rest is automatically saved. In fact I don't even have to use the save method!
Ex: I have teachers and students joined together in courses. A course belongs to many teachers (yes my classes have many teachers per class) and many students. Students have teachers through courses, etc. I've found that if I say
@course -= [@student]
or
@course += [@teacher]
Then I never need to use @course.save or update or anything. It saves itself. This is expected behavior!
Now for my question. Most of my associations work this way (no save needed), so I find it annoying that in one piece of my Schema I need to use the save command, but get to skip that step for everything else. (I want a more consistent frame work, either always use save or never use it.)
You see, my students are grouped into households (two students can be from the same household). So students belong to households, households has_many students etc.
If I need to change the address of my household I have to use
@household.address = "new address"
@household.save
So I want an autosave option for the entire Household model! I see autosave options for associations but I don't need any cascading saving when save is called, I just plain don't want to be bothered calling save at all!
Upvotes: 0
Views: 114
Reputation: 4860
I never seen this feature you want to achieve in Rails and I am pretty sure that does not exists. Otherwise imagine that you have to set several attributes of your model, you will be executing one sql instructions each time you change an attribute.
If you want to add this kind of functionality you can achieve it overriding your address setter to save the model after being set.
def address=(value)
@address = value
self.save
end
I will recommend you a better option, just use this one-line syntax to set and save the object
@household.update_attributes(:address => "new address")
Upvotes: 2