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

Add ActiveRecord::Relation#structurally_compatible?. #41841

Merged
merged 2 commits into from Aug 4, 2021

Conversation

kddnewton
Copy link
Contributor

Summary

Adds a query method by which a user can tell if the relation that they're about to use for #or or #and is structurally compatible with the receiver.

Other Information

Previously you either needed to iterate over the values of the relation or just catch the ArgumentError thrown by #or or #and in order to determine if two relations were structurally compatible.

As for my use case: I have filters coming in from query parameters that are transformed into ActiveRecord::Relation objects. Those objects are then joined together using or and and to get to one single relation at the end. The issue is, if a developer adds a join into any of the transformations, then all of the sudden we've got structurally incompatible relations and some filters can't be used with others. What I'd like to do in this case is:

relations = [...]
relations.drop(1).inject(relations.first) do |current, other|
  if current.structurally_compatible?(other)
    current.or(other)
  else
    Model.where(id: current).or(Model.where(id: other))
  end
end

or something to that effect, so that I don't have to catch any errors and devs can use whatever grouping/joins they want to to get the filters working correctly.

@kddnewton kddnewton force-pushed the structurally-compatible branch 3 times, most recently from 0409b85 to b02c66e Compare April 10, 2021 20:36
@rails-bot
Copy link

rails-bot bot commented Jul 9, 2021

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
Thank you for your contributions.

@rails-bot rails-bot bot added the stale label Jul 9, 2021
@rails-bot rails-bot bot removed the stale label Jul 10, 2021
@kddnewton kddnewton force-pushed the structurally-compatible branch 3 times, most recently from cd99ad6 to e19ab96 Compare July 15, 2021 13:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants