Bahaïka
Bahaïka

Reputation: 725

Multiple models in controller, what good practices with rails 4?

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

Answers (1)

khaled_gomaa
khaled_gomaa

Reputation: 3412

According to what I've got from you.

  1. This controller should be InterestPoints Controller as its main function is to display a list of all Interest points.
  2. The interest point model should contain a method to retrieve all interest points located in a given city and falling under a given sub category and you just call it in the controller.

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

Related Questions