scopes with lambda and arguments in Rails 4 style?

前端 未结 6 918
长情又很酷
长情又很酷 2020-12-04 06:34

I\'m wondering how the following is done in Rails 4 or if I just use the Rails 3 approach for using a lambda that can pass an argument the same way with 4 as I do with 3.

相关标签:
6条回答
  • 2020-12-04 07:04
    scope :find_lazy, -> (id) { where(id: id) }
    

    is equivalent with

    self.find_lazy(id)
      where(id: id)
    end
    

    Based on ruby on rails guide: Using a class method is the preferred way to accept arguments for scopes.

    There is no reason to use scopes together with lambdas in preference to class methods. It is a matter of personal preference. But, if you want to follow the guidelines, you should use the class method when arguments are involved.

    0 讨论(0)
  • 2020-12-04 07:10

    guy I was usually using the below programming syntax

    scope :find_lazy, -> (id) { where(id: id) }
    

    But when I was reviewing my code using Codacy I found it alerting me about this syntax

    Use the `lambda` method for multiline lambdas.
    

    I changed it to be and it working well

      scope :find_lazy, lambda {|id|
        where(id: id)
      }
    
    0 讨论(0)
  • 2020-12-04 07:11

    I think it should be:

    scope :find_lazy, -> (id) { where(id: id) }
    
    0 讨论(0)
  • 2020-12-04 07:13

    To support associations:

    scope :find_lazy, -> (object) { where(object_id: object.id) }
    
    0 讨论(0)
  • 2020-12-04 07:25

    Rails 4, you can do:

    scope :find_lazy, -> (id) { where(id: id) }
    

    That was in the old ruby:

    :id => id
    

    Better hash:

    id: id
    
    0 讨论(0)
  • 2020-12-04 07:27

    Ruby has not deprecated the old style of lambda either, so if you feel more comfortable using that by all means go for it.

    I don't personally like the stabby lambda's syntax myself but eventually they will probably become the norm so it doesn't hurt to get used to them.

    0 讨论(0)
提交回复
热议问题