Reputation: 725
I'm currently developing a web application using Ruby on Rails. I have a controller which get two parameters :city
and :sub_category
.
I've a model named InterestPoint
which belongs to a SubCategory
and a City
Using what I read on the web, I end up doing this to list all InterestPoint
matching the city and the category :
class SubCategoryController < ApplicationController
def index
@city = City.where(route_str: params[:city]).first
@sub_category = SubCategory.where(route_str: params[:sub_category]).first
@interest_point = InterestPoint.where(city_id: @city.id).where(sub_category_id: @sub_category.id)
end
end
My models :
class SubCategory < ActiveRecord::Base
has_many :interest_points
end
class City < ActiveRecord::Base
has_many :interest_points
end
class InterestPoint < ActiveRecord::Base
belongs_to :sub_category
belongs_to :city
end
Here is the route concerned :
get '/:city/:sub_category/' => 'sub_category#index'
It's running well, but RubyMine (my IDE) keeps telling me this is a bad practice : Only one model per controller should be used.
So, my question is, why is it a bad practice, and how can I do it "the right way" ?
My answer based on khaled_gomaa one :
Step 1, moved from SubCategory Controller to InterestPoint Controller since it's what the page is about.
Step 2, created scopes inside my InterestPoint Model :
scope :by_location, lambda { |str|
joins(:city).where('cities.route_str = ?', str)
}
scope :by_category, lambda { |str|
joins(:sub_category).where('sub_categories.route_str = ?', str)
}
Step 3, added Index action to my InterestPoint Controller :
def index
@interest_points = InterestPoint.by_location(params[:city]).by_category(params[:sub_category]).load
end
Upvotes: 0
Views: 409
Reputation: 3412
According to what I've got from you.
So you'll have something like this
class InterestPointsController < ApplicationController
def index
@interest_point = InterestPoint.located(params[:city]).categorized(params[:sub_category])
end
end
where in located and categorized are scopes in the interest point model
Upvotes: 1