Asso:
I'm building a rails app and I have a search query using scope. The code is working but I'm pretty sure it's not written the best way and I would like to improve it to be more reliable in the futur if I want to add some stuff for example.
This is my view :
Here already, I'm refreshing the page to "Reset" the filters. Is it a good option ?
My controller :
@search = SpendingSearch.new(params[:search])
My helper :
@search.scope.order('date DESC').paginate(:page => params[:page], :per_page => 10)
And finally my model which is only created for this search purpose :
class SpendingSearch
attr_reader :date_from, :date_to, :user_id, :currency_id
def initialize(params)
params ||= {}
@date_from = parsed_date(params[:date_from], 1.month.ago.to_date.to_s)
@date_to = parsed_date(params[:date_to], Date.tomorrow.to_s)
@user_id = params[:user_id]
@currency_id = params[:currency_id]
end
def scope
if @user_id.present? && @currency_id.present?
Spending.where("date BETWEEN ? AND ? AND user_id = ? AND currency_id = ?", @date_from, @date_to, @user_id, @currency_id)
elsif @user_id.present?
Spending.where("date BETWEEN ? AND ? AND user_id = ?", @date_from, @date_to, @user_id)
elsif @currency_id.present?
Spending.where("date BETWEEN ? AND ? AND currency_id = ?", @date_from, @date_to, @currency_id)
else
Spending.where("date BETWEEN ? AND ?", @date_from, @date_to)
end
end
private
def parsed_date(date_string, default)
Date.parse(date_string)
rescue ArgumentError, TypeError
default
end
end
As you can see the worst is here... This scope is a little bit ridiculous.
Basically I'm looking for dates, user_id and currency_id. If the currency_id and the user_id are left blank (as I include blank in the view) I want the result to show all the user_id and the currency_id.
I'm sure there is a better way of doing this, I just don't know which one it could be.
Again, I know it's the point to give me the code, I'm just looking to improve here, so anything like, maybe you should check that out or here is a link that could help would be very nice.
Maybe I should change everything and I just don't know, I'm not a rails expert, any tips, tricks or hint is very appreciate.
Thank you very much.
Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE