2

I wanted to create a default value for :order:

class Comment < ActiveRecord::Base
  default_scope :order => 'total_votes DESC'

I'm also letting users to sort the comments:

posts_controller.rb:

@posts = current_user.subscribed_posts.paginate(:page => params[:page],
                                                :per_page => 5,
                                                :order => params[:order_by])

posts/show.html.erb:

<span><%= link_to 'Date (DESC)', post_path(@post, :order_by => "created_at DESC") %></span>
<span><%= link_to 'Date (ASC)', post_path(@post, :order_by => "created_at ASC") %></span>
<span><%= link_to 'Votes', post_path(@post, :order_by => "total_votes DESC") %></span>

It doesn't matter which link I press, the default_scope is not being overwritten (it stays as total_votes DESC no matter what).

Is this the default behavior? If so, what's the right solution for this situation? (I want to have a default value for :order but be able to change it to the value of :order_by once a link in show.html.erb is clicked).

alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • 1
    Have you gone through these: http://stackoverflow.com/questions/1834159/overriding-a-rails-default-scope http://stackoverflow.com/questions/1648971/rails-why-is-with-exclusive-scope-protected-any-good-practice-on-how-to-use-it – Nilesh Mar 12 '12 at 11:42

1 Answers1

1

Are you on Rails 3? If so, you want either reorder(params[:order_by]) or except(:order).order(:order_by) - the former was deprecated at one point (but I think then un-deprecated), the latter had a bug with default scopes in one of the Rails versions, but I forget which.

So: @posts = current_user.subscribed_posts.reorder(params[:order_by]).paginate(:page => params[:page], :per_page => 5) should do the trick.

Shaun
  • 549
  • 3
  • 10