如何使用兰萨克过滤枚举



我正在使用洗劫的宝石

我有一个属性为 :status 的订单表。

:statusorder.rb 中设置为枚举

class Order < ApplicationRecord
  enum status: [:pending, :paid, :sent, :cancelled, :refunded]
  scope :pending,   -> { where(status: :pending) }
  scope :paid,      -> { where(status: :paid) }
  scope :sent,      -> { where(status: :sent) }
  scope :cancelled, -> { where(status: :cancelled) }
  scope :refunded,  -> { where(status: :refunded) }
  def self.ransackable_scopes(auth_object = nil)
    [:pending, :paid, :sent, :cancelled, :refunded]
  end
end

order_controller.rb

def index
    @q = Order.ransack(params[:q])
    @orders = @q.result(distinct: true)
end
def search
  index
  render :index
end

路线.rb

    resources :orders, only: [:index, :show] do 
        collection do
            match 'search' => 'orders#search', via: [:get, :post], as: :search
          end
    end

在我的索引.html.erb中,我有一个订单的汇总表

我想要按钮待处理 - 已付款 - 已发送,当我单击时,它会按状态显示订单......

我试过这个,它没有过滤...

        <%= search_form_for @q, url: search_orders_path, html: {method: :post} do |f| %>
            <%= f.hidden_field :pending %>
            <%= f.submit "Pending", class: "btn btn-success" %>
        <% end %>
        <%= search_form_for @q, url: search_orders_path, html: {method: :post} do |f| %>
            <%= f.hidden_field :paid %>
            <%= f.submit "Paid", class: "btn btn-success" %>
        <% end %>

<% @orders.each do |order| %>
    <tbody>
      <tr>
        <td>FR-000<%= order.user.id %></td>
        <td><%= order.user.last_name %> </td>
        <td><%= order.user.first_name %></td>
        <td>#00<%= order.id %></td>
        <td><%= order.status %></td>
    </tr>
  </tbody>
<% end %>

我没有兰桑克...

订单.rb

class Order < ApplicationRecord
  belongs_to :user
  has_many :items, class_name: "OrderItem", dependent: :destroy
  enum status: [:pending, :paid, :sent, :cancelled, :refunded]
  scope :pending,       -> { where(status: :pending) }
  scope :paid,          -> { where(status: :paid) }
  scope :sent,          -> { where(status: :sent) }
  scope :cancelled, -> { where(status: :cancelled) }
  scope :refunded,  -> { where(status: :refunded) }

  scope :filter_by_status, -> (status) do
    send(status)
  end
end

我创建了一个 orders_helper.rb

module OrdersHelper
    def orders_filtered_by_status
        [:pending, :paid, :sent, :cancelled, :refunded]
    end
end

在我的orders_controller.rb

def index
        @orders = Order.all
        @orders = @orders.filter_by_status(params[:status])if params[:status]
    end

最后在我看来订单/索引.html.erb

<% orders_filtered_by_status.each do |status| %>
  <li class="tabs-bar__item">
    <%= link_to "#{status}", status: status %>
  </li>
<% end %>

最新更新