使用Ransack在Enum字段上搜索

时间:2016-05-16 15:41:11

标签: ruby ransack

我有一张桌子,'工作'有枚举字段'状态'。 status具有以下枚举集:

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Partial Class admin_cadastro
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then marca() End
End Sub

Public Class Marca
    Public Property Codigo() As Integer
        Get
            Return m_Codigo
        End Get
        Set(value As Integer)
            m_Codigo = value
        End Set
    End Property
    Private m_Codigo As Integer
    Public Property Descricao() As String
        Get
            Return m_Descricao
        End Get
        Set(value As String)
            m_Descricao = value
        End Set
    End Property
    Private m_Descricao As String
End Class

<WebMethod>
Public Shared Function GetMarcas() As List(Of Marca)
    Dim dt As New DataTable()
    Dim objMarca As New List(Of Marca)()

    Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
        Using cmd As New SqlCommand("exec sp_ListaMarcas", con)
            con.Open()
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            If dt.Rows.Count > 0 Then
                For i As Integer = 0 To dt.Rows.Count - 1
                    objMarca.Add(New Marca() With {
                        .Codigo = Convert.ToInt32(dt.Rows(i)("Codigo")),
                        .Descricao = dt.Rows(i)("Descricao").ToString()
                    })
                Next
            End If
            Return objMarca
        End Using
    End Using
End Function





End Class

使用ransack,如何过滤表格,比如所有活动记录?

2 个答案:

答案 0 :(得分:7)

你可以在模型中声明自己的ransacker:

ransacker :status, formatter: proc {|v| statuses[v]} do |parent|
  parent.table[:status]
end

然后您可以使用默认的ransack语法_eq来检查这样的相等性:

Model.ransack(status_eq: 'active').result

编辑:如果列名未更改,则可以跳过代码块:

ransacker :status, formatter: proc {|v| statuses[v]}

答案 1 :(得分:6)

这是我在enums和ransack的观点中使用的内容:

<%= f.select :status_eq, Model.statuses.to_a.map { |w| [w[0].humanize, w[1]] },
                         {:include_blank => true} %>