The author is ready to be your mentor and will help you to max out your Ruby on Rails skills first of all we do a search in a default selection.All the logic is explained in a call method: Thus the class is rather large, but one class is one task and it’s also easier to read. where ( 'price sort_direction ) end private def paginate ( scoped, page_number = 0 ) scoped. where ( 'price > ?', from_price ) : scoped to_price ? scoped. where ( "title ILIKE '%?%'", query ) : scoped end private def filter_by_price ( scoped, from = nil, to = nil ) from_price ? scoped. # app/queries/find_products.rb class FindProducts attr_accessor :initial_scope def initialize ( initial_scope ) = initial_scope end def call ( params ) scoped = search ( initial_scope, params ) scoped = filter_by_price ( scoped, params, params ) scoped = filter_by_properties ( scoped, params ) scoped = filter_by_category ( scoped, params ) scoped = sort ( scoped, params, params scoped = paginate ( scoped, params scoped end private def search ( scoped, query = nil ) query ? scoped. Thus we will hide all the logic behind a‘concise’ name FindProducts. Well, let’s let’s put all that into a separate class, which we will call. Moreover, I have some experience in writing things like that and the odder and more cumbersome variants are quite common.Īnd if you look at all the action here, you’ll see that it’s simply a large database query. It’s neat enough, considering that not all the variants but only the basic ones are mentioned here. where ( 'price > ?', from_price ) if from_price to_price = params =. where ( "title ILIKE '%?%'", search ) if search from_price = params =. First of all, let’s see how it might look in the controller and then with the service object.ĭef index = Product. Let’s look at how to use this class using an Internet store and its merchandise list as an example. And when we talk about Rails, we mean ActiveRecord. So, what is a query-object? It’s an object which allows writing big and complex SQL-query with ORM. It’s clear that the list might go on, but for today we have a topic to discuss and it’s about Query-objects.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |