I have just converted into sunspot but am having problems geting my
sorting of columns to work in the controller. My old controller action
looked like this:

def index
  @user = current_user
  @products = @user.products.search(params[:search]).order(sort_column +
' ' + sort_direction)
end

However I haven't been able to apply this into my new controller action.

Any ideas?

My complete application:


models/product.rb:

class Product < ActiveRecord::Base
  attr_accessible :ean, :name, :price, :stock, :user_id, :sku
  belongs_to :user

  validates :user_id, presence: true

  searchable do
    text :ean, :sku, :name
  end
end


controllers/products_controller.rb:

class ProductsController < ApplicationController

  helper_method :sort_column, :sort_direction

  def index
    @user = current_user
    @search = @user.products.search do
      fulltext params[:search]
    end
    @products = @search.results
  end

  private

  def sort_column
    Product.column_names.include?(params[:sort]) ? params[:sort] :
"name"
  end

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


views/products/index.html.erb:

<%= form_tag products_path, :method => :get, :id => "products_search" do
%>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil, class: "btn btn-large
btn-primary" %>
  </p>
  <div id="products"><%= render 'products' %></div>
<% end %>


views/index.js.erb:

 $('#products').html('<%= escape_javascript(render("products")) %>');


views/products/_products.html.erb:

<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<table class="pretty">
  <tr>
    <th><%= sortable "sku", "SKU" %></th>
    <th><%= sortable "name", "Name" %></th>
    <th><%= sortable "stock", "Stock" %></th>
    <th><%= sortable "price", "Price" %></th>
    <th><%= sortable "ean", "EAN" %></th>
  </tr>
  <% for product in @products %>
  <tr>
    <td><%= product.sku %></td>
    <td><%= product.name %></td>
    <td><%= product.stock %></td>
    <td><%= product.price %></td>
    <td><%= product.ean %></td>
  </tr>
  <% end %>
</table>


assets/javascripts/application.js:

$(function () {
  $('#products th a').live('click',
    function () {
      $.getScript(this.href);
      return false;
    }
  );

  $('#products_search input').keyup(function () {
    $.get($("#products_search").attr("action"),
$("#products_search").serialize(), null, 'script');
    return false;
  });
});

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to