Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

alize don't works when the relation is assigned in a callback #36

Closed
rjurado01 opened this issue Mar 3, 2014 · 3 comments
Closed

alize don't works when the relation is assigned in a callback #36

rjurado01 opened this issue Mar 3, 2014 · 3 comments

Comments

@rjurado01
Copy link

I have two classes:

class ClassA
  include Mongoid::Document
  include Mongoid::Alize

  field :text
  has_many :class_b
end
class ClassB
  include Mongoid::Document
  include Mongoid::Alize

  belongs_to :class_a
  alize_from :class_a, :text

  before_create do
    self.class_a = ClassA.create(text: 'Hello')
  end
end

If I do this, alize don't work:

b = ClassB.create
 => #<ClassB _id: 5314662b7cf978428a000002, class_a_id: "5314662b7cf978428a000001", class_a_fields: {}> 
b.reload.class_a.text
 => "Hello" 
b.class_a_fields
 => {} 

When Alize is executed ?

@joshed-io
Copy link
Owner

Alize puts "from" callbacks in before_save. Per Rails callbacks before_save is fired before before_create. Furthermore, since alize_from is above the before_create block in ClassB, it would add its callback too early even if it was before_save. Here are some options to work around this.

Option 1 - manually call denormalize_from_all

 before_create do
    self.class_a = ClassA.create(text: 'Hello')
    self.denormalize_from_all
  end

Option 2 - Use before_save, and put alize_from after the before_save callback

class ClassB
  include Mongoid::Document
  include Mongoid::Alize

  belongs_to :class_a

  before_save do
    self.class_a = ClassA.create(text: 'Hello')
  end

  alize_from :class_a, :text
end

@rjurado01
Copy link
Author

Thanks !!

@joshed-io
Copy link
Owner

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants