Yêu cầu thg 6 10, 7:29 SA 89 0 3
  • 89 0 3
0

cách sử dụng ransackable_scopes trong ROR

Chia sẻ
  • 89 0 3

model code:

     scope :with_active_subscription, -> (flag = nil) {
        pp "Value received: #{flag.inspect}"
        return all if flag.blank? || flag.to_s == ''

        if flag.to_s == 'true'
          # Logic cho true case
          where(has_active_subscription: true)
        elsif flag.to_s == 'false'
          # Logic cho false case  
          where(has_active_subscription: false)
        else
          all
        end
      }

      class << self
        def ransackable_scopes(auth_object = nil)
          %w[with_active_subscription]
        end
      end

controller code:

# GET /products
  def index
    @q = Product.ransack(search_params)
    @products = @q.result(distinct: true)
  end

  private

    def search_params
    params.fetch(:q, {}).permit(
      :with_active_subscription,
    )
  end

=> hiện không nhận được giá trị của flag trong "scope :with_active_subscription", mọi người giúp mình với.

3 CÂU TRẢ LỜI


Đã trả lời thg 6 23, 7:39 SA
0
class << self
  def ransackable_scopes(auth_object = nil)
    [:with_active_subscription] # <-- dùng symbol
  end
end
Chia sẻ
Đã trả lời thg 6 23, 7:47 SA
0

Theo ý kiến cá nhân của mình, thì có thể sửa lại code cho gọn như sau:

# GET /products
  def index
    @products = Product.with_active_subscription(params[:is_active_subscription])
  end

# model
  scope :with_active_subscription, -> (flag) {
    flag = ActiveModel::Type::Boolean.new.cast(flag)
    return if flag.blank?

    where(has_active_subscription: flag)
  }
Chia sẻ
Đã trả lời thg 7 15, 3:24 SA
0

Interesting article on ransackable_scopes in Rails! I found it particularly helpful for creating custom search logic. I'd suggest adding examples showcasing how to use these scopes with complex queries, perhaps involving multiple tables. I use this when playing Wordle Unlimited , so the search logic is important. Is there any consideration on using ransackable_scopes when it comes to performance? I'm thinking about scaling the app in the near future. Thanks for the insights!

Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí