如標題所示,我試圖顯示上/下箭頭。目前建立在Ruby 2.0/Rails 4.0上如何顯示基於排序asc/desc的箭頭(RoR 4)
我已經遵循關於排序表列(http://railscasts.com/episodes/228-sortable-table-columns)的railscasts,但他當然使用表格,所以他的箭頭顯示得很好。
我想使用divs/span /其他任何東西。 (這不是很多數據,它不是需要在表中的數據類型。)
這就是說,我去爲我的箭頭做一個應用程序幫手的方法,他們的工作,但如果我點擊一個asc,兩個箭頭都會指向。如果我點擊一個desc,兩者都指向下。顯然,因爲params[:direction]
被設置爲asc或desc,所以兩個箭頭都被設置。我如何區分它們?在某種程度上僞代碼:
if title && asc
sort by title and asc && show up arrow (for title only)
if title && desc
sort by title and desc && show down arrow (for title only)
if date posted && asc
sort by created_by and asc && show up arrow (for date posted only)
etc.
我真的不想有一個巨大的if/then條件聲明,但想要更簡單。
(如推來推去,我只使用一個表的排序方式:部分,但只是似乎真的非常愚蠢的,這是一個有點不得已......)
下面是代碼我有:
show.html.erb
<h3>Images</h3>
<% if @user.images.any? %>
<div class="sortable"><%= sortable "img_name", "Title" %><%= arrow %> |
<%= sortable "created_at", "Date posted" %><%= arrow %>
</div>
<%= render @images %>
<%= will_paginate @images %>
<% end %>
application_helper.rb
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, {sort: column, direction: direction}, {class: css_class}
end
def arrow
if params[:direction] == 'asc'
image_tag("arrow_up.png", alt: "up arrow", size: "15x15")
elsif params[:direction] == 'desc'
image_tag("arrow_down.png", alt: "down arrow", size: "15x15")
else
# either a blank image to show or just force no-display of image
end
end
users_controller.rb
def show
@user = User.find(params[:id])
@images = @user.images.paginate(page: params[:page]).order(sort_column + " " + sort_direction)
end
private
def sort_column
Image.column_names.include?(params[:sort]) ? params[:sort] : "created_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
嗯,我想這一點,並沒有奏效。兩支箭都同時朝上或朝下。我已決定爲排序鏈接創建一個表格,並嘗試使其以這種方式工作。 :\一旦我完全工作,我會張貼我的解決方案。 –
我想你一定錯過了什麼(或者我錯過了什麼)。請注意我的箭頭助手的第一行。應該只有一個箭頭,即當前正在排序的列的箭頭。如果該列不是要排序的列,則它將返回空字符串而不是圖像標記。 – numbers1311407