ActiveRecord should provide a convenient way for a model object to exclude itself from a scope #8297

Closed
betesh opened this Issue Nov 23, 2012 · 3 comments

2 participants

@betesh

In addition to handling an exception thrown when uniqueness is validated upon saving a record, I often find it necessary to check whether a given record has some unique attribute when no writing to the database is necessary. The code usually looks something like this:

class MyModel < ActiveRecord::Base
  def  all_other_records_in_some_class_method_or_scope
    return self.class.some_class_method_or_scope if self.new_record?
    self.class.with_scope(self.class.where('id != ?', self.id)) do
      self.class.some_class_method_or_scope
    end
  end
end

(The reason for the early return when new_record? == true is that self.id doesn't usually behave nicely for unsaved records.)

ActiveRecord::Base could encapsulate this logic so that this code would be reduced to the following:

class ActiveRecord::Base
  def  all_other_records_in scope
    return self.class.__send__(scope) if self.new_record?
    self.class.with_scope(self.class.where('id != ?', self.id)) do
      self.class.__send__(scope)
    end
  end
end
class MyModel < ActiveRecord::Base
  def  all_other_records_in_some_class_method_or_scope
    all_other_records_in :some_class_method_or_scope
  end
end

Note that the scope argument need not be a scope. Any class method with any return type should be valid.
I submit this feature to the Rails team because I strongly suspect my implementation is far from optimal but don't know my way around ActiveRecord well enough to know of a better solution.

@carlosantoniodasilva
Ruby on Rails member

Please send your feature request to the Rails Core mailing list, or try to propose it in a pull request, to gather more people discussing about it. Lets keep the issues tracker for issues ;). Thanks!

@betesh
@carlosantoniodasilva
Ruby on Rails member

@betesh no problem. The best ways to initiate a discussion about a new feature is to either try the rails core mailing list to get some feedback first, or go straight to the code and put up a pull request showing your intents. When in doubt, the core list + some code examples is the best to start with.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment