开发者

Chaining searching and sorting together in rails using serachlogic

My code is very similar to that in railscasts #240

The differences are that I am using rails 2.3.10 so I am not using 'where'. Instead I am using serachlogic and my model looks like this...

//Model.rb
def self.search(search)
      if search
        Model.column_name_like(search)
      else
        find(:all)
      end
    end

(I am using search logic because I need case insensitivity because I am deploying to heroku(postgres))

When I try and chain my methods together like in the railsc开发者_StackOverflow中文版ast and in other tutorials I get an error such as "method order not found"

My controller is here...

 @objects=Model.search(params[:search]).order(sort_order('created_at'))

This is with a slightly different column sort method which was working for me before I stuck the search in.

Why does this method work in some tutorials but throwing an error in this case. Is it because the tutorials are in rails 3?


I found an optimal solution myself a few days later. I had to make a change in my model. Instead of returning a find(:all) in the else I returned a new "empty"search object

@search=Model.column_name_like("")

Fore reference my model and controller which now supports sorting,searching, and pagination looks like...

def self.search(search)
      if search
        Model.column_name_like(search)
      else
        @search=Model.column_name_like("")
      end
    end

def index
  @per_page = params[:per_page] || Lease.per_page || 20
  @search=Lease.search(params[:search])
  @objects=@search.find(:all, :order=>(sort_column + " "+ sort_direction)).paginate(:per_page => @per_page, :page => params[:page])
end

private 
def sort_column
  Model.column_names.include?(params[:sort]) ? params[:sort] : "default_column_name"
end

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

Don't forget to put hidden form helpers in your view to pass in the column name and direction.

<p>
<% form_tag leases_path, :method => 'get' do %>
<p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
</p>
<%=hidden_field_tag :direction, params[:direction]%>
<%=hidden_field_tag :sort, params[:sort]%>

<% end %>


That railscast doesn't appear to be using searchlogic which explains why this is not working. It is using rail3's new Active Record (Arel) libraries to accomplish a searchlogic-like behavior.

Instead of:

@objects=Model.search(params[:search]).order(sort_order('created_at'))

Try:

@objects=Model.search(params[:search]).ascend_by_created_at

Or:

@objects=Model.search(params[:search]).descend_by_created_at

cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜