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

Unscoping mutiple models #458

Open
jdejong opened this issue Dec 11, 2018 · 0 comments
Open

Unscoping mutiple models #458

jdejong opened this issue Dec 11, 2018 · 0 comments
Labels

Comments

@jdejong
Copy link

jdejong commented Dec 11, 2018

I have an interesting issue. We are implementing sharding in our data and it is causing issues for soft-deleted data. The major issue is polymorphic relationships while trying to calculate the shard key.

For example...

class Question < ActiveRecord::Base
    acts_as_paranoid
    belongs_to :questionable, polymorphic: true

    before_save :calculate_company_id, if: :questionable_id_changed?

    def calculate_company_id #shard key
        self.company_id = self.try(:questionable).try(:company_id)
    end
end
class Survey < ActiveRecord::Base
    acts_as_paranoid
    belongs_to :company
    has_many :questions, as: :questionable
end
class Quiz < ActiveRecord::Base
    acts_as_paranoid
    belongs_to :company
    has_many :questions, as: :questionable
end

If we have a soft deleted Quiz and a Question that is associated with that soft deleted Quiz and you call the calculate_company_id method, then nil is returned. In order to get this to work, adding unscoped around the code in question self.company_id = self.try(:questionable).try(:company_id) will solve this, but you need nested unscoped blocks. For example...

class Question < ActiveRecord::Base
    acts_as_paranoid
    belongs_to :questionable, polymorphic: true

    before_save :calculate_company_id, if: :questionable_id_changed?

    def calculate_company_id #shard key
        Quiz.unscoped do
            Survey.unscoped do
                self.company_id = self.try(:questionable).try(:company_id)
            end
        end
    end
end

so that it works for both related object types. Is there a way to do this without having to nest the blocks and still accomplish the same outcoming? Thanks for any help!

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

No branches or pull requests

2 participants