jeudi 14 mai 2015

Passing params without nil

I want to pass the value of a form to a Controller that should call a method from the Model for searching products

i want to pass category_id and the string that the user writes in the textfield. I would pass to the model even the blank value of params (if the user doesn't writes nothing on the search bar or choose none category) I want to save even the blank value cause in the Model, the SQL blank variable take "all" things. And this is good cause if there is something in params , the SQL will find that thing BUT if in params there isn't something , the SQL will take all products.

I'm not able to save the value of params in varibiles cause if params is blank it returns to me this error:

undefined method `[]' for nil:NilClass

I hope you understand me and what i want to do. In other words , i want to use a simple assignament to pass value (even blank value) to a model to do a SQL query. In one shoot of code i want to program two cases.

Here my code.

In my Controller:

...

if params[:search]
    @search_name = params[:search]
end

if params[:category][:name]
    @category = params[:category][:name]
end 

@products = Product.search(@search_name,@category)

...

In my Model:

def self.search(search_name,category)
    ricerca = Product.where("category_id = ? ",category)
    ricerca = ricerca.where("title like ? ", "%#{search_name}%") 
end

Aucun commentaire:

Enregistrer un commentaire