2016-04-04 56 views
0

我有一个表,可以通过消息进行排序以及发送时间。现在,当用户进入页面时,首先从订购邮件正文开始,我希望它以用户启动页面时的时间desc开始。我将展示一些代码和截图。我还在railscast#228上找到了这段代码。自动排序的位置?

以下是对它们进行排序的方法。

def sort_column 
    Message.column_names.include?(params[:sort]) ? params[:sort] : "body" 
end 

def sort_direction 
    %w(asc desc).include?(params[:direction]) ? params[:direction] : "asc" 
end 

下面是这个视图

<tbody> 
    <% @message.each do |message| %> 
     <tr> 
     <td><%= message.body %></td> 
     <td><%= time_ago_in_words message.created_at %> ago</td> 
     <td><%= message.groups.order(:id).pluck(:name).to_sentence %></td> 
     </tr> 
    <% end %> 
    </tbody> 

该用户所看到的,当他们打开网页,你可以看到的箭头上的消息。我希望箭头在方向desc处“发送”。

enter image description here

我不知道这是否是足够的信息,但让我知道!

回答

1

sort_columnsort_direction功能默认为"body""asc"

如果你想默认的排序顺序默认为created_at,转变职能,像这样:

def sort_column 
    Message.column_names.include?(params[:sort]) ? params[:sort] : "created_at" 
end 

def sort_direction 
    %w(asc desc).include?(params[:direction]) ? params[:direction] : "desc" 
end 
+0

你是正确的,但我有这些方法对两个不同的表。所以如果我这样做,它会错误地格式化我的其他观点。有什么建议么? – Bitwise

+0

在这一点上你可以做的事情有很多种选择。一个简单的地方就是编辑你的'sort_column'方法来使用类变量,如 'Message.column_names.include?(params [:sort])? params [:sort]:@default_sort_column || “created_at”' 然后在操作中,设置'@ default_sort_column'变量 –

+0

我对ruby有点新,你可以用这个注释编辑你的答案,以使它对我更清楚吗? – Bitwise

1

如果你只是想显示按创建日期的消息,拉“时间在这样的索引操作:

Message.order(created_at: :desc)