Ruby on rails 删除只改变顺序的查询

Ruby on rails 删除只改变顺序的查询,ruby-on-rails,ruby-on-rails-4,rails-activerecord,Ruby On Rails,Ruby On Rails 4,Rails Activerecord,我会根据用户是否点击了“趋势”、“新”或“热门”对我的“帖子”进行不同的排序 有很多重复的代码,但我不确定如何计算出订单的内容一种方法就是: CHOSEN_ATTRIBUTES = {'trending' => 'trending_score', 'new' => 'created_at', 'top' => 'total_votes'} #this could be a constant up in the class chosen_attr = CHOSEN_ATTRIBU

我会根据用户是否点击了“趋势”、“新”或“热门”对我的“帖子”进行不同的排序


有很多重复的代码,但我不确定如何计算出
订单的内容

一种方法就是:

CHOSEN_ATTRIBUTES = {'trending' => 'trending_score', 'new' => 'created_at', 'top' => 'total_votes'} #this could be a constant up in the class
chosen_attr = CHOSEN_ATTRIBUTES[params[:sort_type]] 
@posts = Post.order("#{chosen_attr} DESC").limit(30)
另一种方法是创建一个带有参数的作用域。在您的模型中:

CHOSEN_ATTRIBUTES = {'trending' => 'trending_score', 'new' => 'created_at', 'top' => 'total_votes'}

scope :order_query_by, lambda {|attr| order("#{CHOSEN_ATTRIBUTES[attr]} DESC").limit(30)}
然后,无论何时根据属性需要调用,请使用:

Post.order_query_by 'trending'

一种方法就是:

CHOSEN_ATTRIBUTES = {'trending' => 'trending_score', 'new' => 'created_at', 'top' => 'total_votes'} #this could be a constant up in the class
chosen_attr = CHOSEN_ATTRIBUTES[params[:sort_type]] 
@posts = Post.order("#{chosen_attr} DESC").limit(30)
另一种方法是创建一个带有参数的作用域。在您的模型中:

CHOSEN_ATTRIBUTES = {'trending' => 'trending_score', 'new' => 'created_at', 'top' => 'total_votes'}

scope :order_query_by, lambda {|attr| order("#{CHOSEN_ATTRIBUTES[attr]} DESC").limit(30)}
然后,无论何时根据属性需要调用,请使用:

Post.order_query_by 'trending'

你能发布你的查看代码吗?我认为更改视图代码会更好。你能发布视图代码吗?我认为更改视图代码可能会更好。