Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling automatic saving through has_many association - Disconnecting ActiveRecord entity from session

The default behaviour for Ruby on Rails is to save changes made to collection associations. Is there any way to change this behaviour, so that I can modify the collections in memory without the changes being written to the database.

So if I have two classes:

class Project < ActiveRecord::Base
  has_many :tasks

class Task < ActiveRecord::Base
  belongs_to :project

and write some code like:

Project.tasks.clear
Project.tasks << task1
Project.tasks << task2

then it automatically deletes all tasks associated with the Project and automatically writes the changes to the db.

This is a contrived example of what I'm trying to achieve. I know I could use Project.tasks.build() to add a new task to the collection without it being saved automatically, but the the tasks that I'm adding are not new tasks.They are links to a limited set of tasks defined in db. You could think of them as entries in an enumeration of tasks. In addition Project.tasks.clear immediately hits the db.

In java world, using Hibernate, I would disconnect the entity from the session and be able to modify the entity in memory until reconnecting and saving.

Thanks

like image 967
ianpetzer Avatar asked Nov 04 '22 20:11

ianpetzer


1 Answers

Have you tried using the task_ids attribute instead?

Change your code to:

Project.tasks_ids = []
Project.tasks_ids << task1.id
Project.tasks_ids << task2.id

I know this question is a bit old, but since I tried to search a similar problem on Google I thought this might be useful to other people.

like image 129
helder.tavares.silva Avatar answered Nov 15 '22 06:11

helder.tavares.silva