简体   繁体   中英

Ruby on Rails Override a method that expects a block

With the new attribute marked_deleted in AssistantTeacher class, We want all queries to work with the basic assumption of only selection where marked_deleted attribute is false.

This is easy (using squeel query language instead of standard AR query language)

class AssistantTeacher < ActiveRecord.Base
    # Gives a default query which always includes the condition here
    default_scope  {where{marked_deleted == false }}
end

This means that queries like AssistantTeacher.all will actually be

AssistantTeacher.all.where{marked_deleted == false}

Works great. Likewise AssistantTeacher.find_each() also works with the limitation. likewise

AssistantTeacher.where{atcode == "MPL"}

also executes as

I

However then the tricky part: We need to reverse the default_scope for admins etc in special cases:

class AssistantTeacher < ActiveRecord.Base
  # Gives a default query which always includes the condition here
  default_scope  {where{marked_deleted == false }}
  # If a query is unscoped then the default_scope limitation does not apply
  # scoped is the default scope when there is no default_scope
  unscoped { scoped}
end

This works fine for

def self.all_including_marked_deleted
    return unscoped{all} 
end

However: the question I can't figure out how to do an unscoped for an admin version of find_each with a block

def self.find_each_including_marked_deleted &block
    return unscoped{find_each(block)} 
end

DOESNOT work. Nor do any other combination with block that I can think of.

Anyone any ideas what I can do to get my overriding method find_each_including_marked_deleted to pass its block to the unscoped call?

You just have a small syntax problem. If you add a & to the front of your block , you should be fine:

def self.find_each_including_marked_deleted &block
    unscoped { find_each &block } 
end

What's going on here? Inside the method body, the block variable is an instance of Proc (that's what the & is doing in front of the block param). You can verify this by checking block.class . find_each takes a block, not a proc, so you need the & to convert the proc back to a block.

Clear as mud? You can read more about it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM