Working with an has_and_belongs_to_many_association
class Category
has_and_belongs_to_many :projects
end
I would would like to use a before_filter to set projects before saving categories
before_filter :set_projects, :only => [:create, :update]
def set_projects
@category.assign_attributes({projects: Project.all})
end
This works well, except when the category cannot be saved and there is a rollback. The projects are still updated in database.
Why this line
@category.assign_attributes({projects: Project.all})
generate these database records immediately?
BEGIN
INSERT INTO "categories_projects" ("category_id", "project_id") VALUES (86, 1)
INSERT INTO "categories_projects" ("category_id", "project_id") VALUES (86, 2)
INSERT INTO "categories_projects" ("category_id", "project_id") VALUES (86, 3)
COMMIT
I would like to wait for @category.save before commiting these new categories_projects relations. How to postpone these commits?
Please note that I can't modify the main "update" action. I have to use before/after filters and callbacks in order to override current functionality of my app.
------ EDIT ----------
Ok, after reading the doc carefully here, I think I have a solution:
When are Objects Saved?
When you assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
If you want to assign an object to a has_and_belongs_to_many association without saving the object, use the collection.build method.
I will try to use the collection.build method. Do you have any idea how to do that with existing projects?