根据参数Rails排序

时间:2017-04-08 17:19:41

标签: ruby-on-rails

我需要根据HKCU:\Console参数中发送的值排序查询。以# Determine the target registry key path. $keyPath = 'HKCU:\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe' # Get the existing key or create it on demand. $key = Get-Item $keyPath -ErrorAction SilentlyContinue if (-not $key) { $key = New-Item $keyPath } # Determine the new size values. [uint32] $cols = 100; [uint32] $lines = 50 # Convert to a DWORD for writing to the registry. [uint32] $dwordWinSize = ($cols + ($lines -shl 16)) # Note: Screen *buffer* values are inherited from # HKCU:\Console, and if the inherited buffer width is larger # than the window width, the window width is apparently set to # the larger size. # Therefore, we must also set the ScreenBufferSize value, passing through # its inherited height value while setting its width value to the same # value as the window width. [uint32] $dwordScreenBuf = Get-ItemPropertyValue HKCU:\Console ScreenBufferSize -EA SilentlyContinue if (-not $dwordScreenBuf) { # No buffer size to inherit. # Height is 3000 lines by default. # Note that if we didn't set this explicitly, the buffer height would # default to the same value as the window height. $dwordScreenBuf = 3000 -shl 16 } # Set the buffer width (low word) to the same width as the window # (so that there's no horizontal scrolling). $dwordScreenBuf = $cols + (($dwordScreenBuf -shr 16) -shl 16) # Write the new values to the registry. Set-ItemProperty -Type DWord $key.PSPath WindowSize $dwordWinSize Set-ItemProperty -Type DWord $key.PSPath ScreenBufferSize $dwordScreenBuf 开头的sort值表示排序应为sort

示例:

  • -应使用desc
  • url/employee?sort=name排序
  • name应使用asc
  • url/employee?sort=-name排序
  • name应使用desc
  • url/employee?sort=last_name排序
  • last_name应使用asc
  • url/employee?sort=-age排序
Ruby on Rails中的

1 个答案:

答案 0 :(得分:0)

您需要检查参数值是否在字符串的开头包含-;如果是,请删除它并使用:desc进行排序,如果它不使用:asc进行排序。

假设您有一个名为Employee的模型和名为EmployeeController的控制器,其行为为index,您可以执行以下操作:

# employee_controller.rb

def index
  attribute = params["sort"].sub("-", "")
  order = define_order(params["sort"])
  @employees = Employees.all.order(attribute => order)
end

private

def define_order(attribute)
    attribute.start_with?("-") ? :desc : :asc
end