views:

38

answers:

2

I have a model "Product" with a "description" field. Now I want to have a link in the index page that when clicked will show all products where the description is blank (empty).

In the model I have defined a named_scope like this

named_scope :no_description,      :conditions => { :description => "" }

I have checked that the named_scope works by calling Product.no_description.count on the console.

As far as I know, the controller is then supposed to handle the filter request from the link on the "index" action but be able to distinguish it from the default which is view all products.

 def index
    @products = Product.all
    ...

My problem is getting the controller handle the different request, what route to setup for the link on the view and the actual link on the view. Hope I explained my problem.

+1  A: 

If your link passes in a parameter, you can check for that and use the named scope in the index action:

def index
    if params[:no_description]
        @products = Product.no_description
    else
        @products = Product.all
    end
end

In your view you can use something like:

link_to('No description', products_path(:no_description => 1))
Jason Weathered
I think you have a typo, it should be `Product.all` etc. (singular). Also, there's a missing bracket at the end of the `link_to`.
John Topley
@John I have fixed these typos. Thanks.
Jason Weathered
+1  A: 

There are two basic approaches you can take. You could set up a new route and controller action for displaying the description-less products, or you could use a query string parameter on the hyperlink to make the distinction. I would go with the second approach to avoid cluttering up the controller with too many actions.

Your link will look something like this, assuming you're using RESTful routing:

<%= link_to 'Products Without Descriptions', products_path(:filter => true) %>

And here's the controller action, which simple looks for the existence of the parameter (i.e. it doesn't care what value it has):

def index
  if params[:filter]
    @products = Product.no_description
  else
    @products = Product.all
  end
  ...
end
John Topley
thanks John, works like a charm
kibyegon