I have tables Houses, Companies, Streets, HouseTypes and a开发者_Python百科ssociated Models.
Each House belong to Company, HouseType and Street
Also I already have correct scopes methods in House Model:
scopes: belong_to_company, on_street, with_type
It is need to make filter in view. But it is possible that user can choose more than one option in filter. He can mark some streets and also he can mark some HouseTypes and some Companies.
So I add such methods in House model:
def self.filter_for_types(company, street, types)
houses = []
each.types do |type|
houses = houses + House.belong_to_company(company).on_street(street).with_type(type)
end
houses.uniq
end
def self.filter_for_streets(company, streets, types)
houses = []
each.streets do |street|
houses = houses + House.filter_for_types(company, street, types)
end
houses.uniq
end
def self.filter(companies, streets, types)
houses = []
each.companies do |company|
houses = houses + House.filter_for_streets(company, streets, types)
end
houses.uniq
end
So in view I have some with it:
def index
House.filter(params[:companies], params[:streets], params[:types])
end
I think that my code is not very well. What can I do with model? (put all code to scopes - seems good idea? )
There are any pretty plugins exist for such view generation?
That's completely acceptable, it's in fact how you're supposed to do on Rails, keep skinny controllers and fat models, once you start to think your models have too much code you can also subdivide these methods into modules, like User::CompanyFilters, where you would place all filters related to companies and keep your code modularized, but this isn't a requirement.
Also, instead of doing uniq on your results, make try to use DISTINCT or GROUP BY on your SQL statements, this way you make sure you're not sending unnecessary information over the wire (from your database) and not creating unecessary ActiveRecord objects, as they are expensive do build and manage.
精彩评论