ruby on rails - Passing params without nil -
i want pass value of form controller should call method model searching products.
i want pass category_id
, string user writes @ textfield
.
pass model blank value of params (if user doesn't write on search bar or choose none category)
want save blank value cause in model, sql blank variable take "all" things. , cause if there in params , sql find thing, if there nothing in params, sql take products.
i'm not able save value of params in varibiles cause if params blank returns me error:
undefined method `[]' nil:nilclass
i hope understand me , want do. in other words , want use simple assignment pass value (even blank values) model sql query. in 1 shoot of code want program 2 cases.
here code.
in 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 model:
def self.search(search_name,category) ricerca = product.where("category_id = ? ",category) ricerca = ricerca.where("title ? ", "%#{search_name}%") end
you can category parameters defining method like,
def category_params params.fetch(:category, {}) end
and, products by,
@search_name = params[:search] @category = category_params[:name] @products = product.search(@search_name, @category)
in opinion, if making direct query on product, should like,
def product_params params.fetch(:product, {}) end @category = product_params[:category_id] @title = product_params[:title] @products = product.search(@category, @title)
and in product model,
def self.search(category, title) where("category_id = ? , title ?", category, "%#{title}%") end
Comments
Post a Comment