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

Avoid overwriting association conditions with default scope in Rails 3 #560

Merged

Conversation

avit
Copy link
Contributor

@avit avit commented Jul 8, 2015

This is a fix on top of my previous pull request #426 where I fixed one bug but potentially introduced another. 🙊

When a model with default scope was associated with conditions (has_many :x, conditions: ...), the default scope would overwrite the association conditions. This patch ensures that both sources of conditions are applied.

if default_conditions.any?
reflection.options[:conditions] = default_conditions
return if reflection.instance_variable_get(:@_ransack_applied_default_conditions)
assoc_scope = join_association.active_record.where(reflection.options[:conditions])

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line is too long. [93/80]

@avit
Copy link
Contributor Author

avit commented Jul 9, 2015

Found issues: it doesn't handle conditions on aliased table names, and I think we can avoid altering the conditions on the original association reflection (this is held by the parent class globally so it's best not to mutate anything on it). I will resubmit with some improvements.

When joining ransackable associations in Rails 3, preserve both:

* association default_scope
* association conditions

Combining the stashed JoinAssociation with a separate string join for
the "AND" conditions looks like a hack, but there is no cleaner way to
extract the default_scope conditions with correct table aliases and
merge them back into the association since ActiveRecord rebuilds its own
join parts when generating the query.
@avit avit force-pushed the association-conditions-rails3 branch from 1be6ff2 to 9f778e8 Compare July 9, 2015 20:42
jonatack added a commit that referenced this pull request Jul 12, 2015
Avoid overwriting association conditions with default scope in Rails 3
@jonatack jonatack merged commit aee1985 into activerecord-hackery:master Jul 12, 2015
@jonatack
Copy link
Contributor

Thanks @avit!
😃

@jonatack
Copy link
Contributor

Could you update the change log with your fix?

jonatack added a commit that referenced this pull request Jul 18, 2015
Completes PRs #562, #498, #426, #560 and #537 among others.
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

Successfully merging this pull request may close these issues.

3 participants