couchrest / couchrest_model

Doing the simple stuff so you don't have to
Apache License 2.0
304 stars 116 forks source link

[back_assignments] create fixture models and spec titles #190

Open yarmand opened 9 years ago

yarmand commented 9 years ago

when two models are referencing each other as associations, affecting one model association attribute will also assign the corresponding attribute in the referenced model. Saving a model will trigger save of associated models.

This reproduce the effect of ActiveRecord on relationel databases. belongs_to and as_many rely on the same foreign key.

*example:

class Parent < CouchRest::Model::Base
  collection_of :children
end

class Child < CouchRest::Model::Base
  belongs_to :dad, class: Parent, :reverse_association => :children
end

bob   = Parent.new
kevin = Child.new
kevin.dad = bob

without back assignments:

bob.children.include? kevin
=> false

with back assignments:

bob.children.include? kevin
=> true

reverse association calculation

back assignment is triggered by the presence of the :reverse_association option.

belongs_to :attr_name, :class_name => 'A class', :reverse_association => :attr_name_in_the_other_model
collection_of :attr_name , :reverse_association => :attr_name_in_the_other_model
samlown commented 9 years ago

Hi! Thanks for submitting this. I can see the benefits, but I can see a fundamental flaw in the implementation. Given that CouchDB does not support transactions, you are opening the floodgates to data inconsistencies by attempting to auto-save the other documents.

In my opinion, all CouchRest Model operations should be atomic, and not have cascading callbacks in order to maintain predictability.

However, I like your refactoring of the "association" parts. If you'd like to submit a pull request with a set of changes to the association handling so that you can turn your changes into another gem, more than happy to add them. A gem called something like couchrest_model_association_saving would work.