Rails 4 scope with argument

后端 未结 2 1847
别跟我提以往
别跟我提以往 2021-01-01 14:34

Upgrading Rails 3.2. to Rails 4. I have the following scope:

# Rails 3.2
scope :by_post_status, lambda { |post_status| where(\"post_status = ?\", post_status         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 14:42

    Very simple, just same lambda without arguments:

    scope :by_post_status, -> (post_status) { where('post_status = ?', post_status) }
    scope :published, -> { by_post_status("public") }
    scope :draft, -> { by_post_status("draft") }
    

    or more shorted:

    %i[published draft].each do |type|
      scope type, -> { by_post_status(type.to_s) }
    end
    

提交回复
热议问题