Argument Error: The scope body needs to be callable

前端 未结 4 1029
南方客
南方客 2020-12-24 01:24

I\'m working through the \'Ruby On Rails 3 Essential Training\' and have received a problem when using name scopes. When finding records and using queries withing the Rails

相关标签:
4条回答
  • 2020-12-24 01:58

    The scope's body needs to be wrapped in something callable like a Proc or Lambda:

    scope :visible, -> {
      where(:visible => true)
    }
    

    The reason for this is that it ensures the contents of the block is evaluated each time the scope is used.

    0 讨论(0)
  • 2020-12-24 02:01

    Yes, indeed, this is rails 4 way of calling scopes. You'd need to change it, if you're upgrading to Rails 4 from Rails 3.

    0 讨论(0)
  • 2020-12-24 02:03

    What you are using: scope :visible, where(:visible => true) goes for eager loading, and has been deprecated in Rails 4.

    scope :visible, where(:visible => true)
    

    This line of code gets evaluated when the particular class is loaded, and not at the time, this very scope is called.

    There are a few cases when this thing does matter, like:

    scope :future, where('published_at > ?', Time.now)
    scope :future, -> { where('published_at > ?', Time.now) }
    

    In first case, ? will be replaced with the very time the class would have been loaded, but the second & correct case, that time will be used at which the scope would have been called on the class.

    0 讨论(0)
  • 2020-12-24 02:07

    I got the same error , while before my solution I had a space between where and ( like below

    scope :registered , -> { where ( place_id:  :place_id , is_registered: :true ) }
    

    after i removed the space between where and ( like below i made my page working

    scope :registered , -> { where( place_id:  :place_id , is_registered: :true ) }
    
    0 讨论(0)
提交回复
热议问题