控制器中的多个型号,使用rails 4有什么好的做法?

时间:2014-03-27 12:56:26

标签: ruby-on-rails ruby-on-rails-4

我目前正在使用Ruby on Rails开发一个Web应用程序。我有一个控制器,它有两个参数:city:sub_category。 我有一个名为InterestPoint的模型,它属于SubCategoryCity

使用我在网上看到的内容,我最终会这样做以列出与城市和类别匹配的所有InterestPoint

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

我的模特:

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

以下是相关路线:

get '/:city/:sub_category/' => 'sub_category#index'

它运行良好,但RubyMine(我的IDE)一直告诉我这是一个不好的做法:每个控制器只应使用一个模型。

所以,我的问题是,为什么这是一种不好的做法,我怎么能以“正确的方式”做到这一点?

我的答案基于khaled_gomaa:

第1步,从SubCategory Controller转移到InterestPoint Controller,因为它是页面的内容。

第2步,在我的InterestPoint模型中创建了范围:

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)
}

第3步,向我的InterestPoint Controller添加了索引操作:

def index
   @interest_points = InterestPoint.by_location(params[:city]).by_category(params[:sub_category]).load
end

1 个答案:

答案 0 :(得分:1)

根据我从你那里得到的东西。

  1. 此控制器应以InterestPoints Controller为主 功能是显示所有兴趣点的列表。
  2. 兴趣点模型应该包含一个方法 检索位于给定城市的所有兴趣点并且下降 在给定的子类别下,您只需在控制器中调用它。
  3. 所以你会有类似的东西

    class InterestPointsController < ApplicationController
    
      def index
        @interest_point = InterestPoint.located(params[:city]).categorized(params[:sub_category])
      end
    end
    

    在位置和分类中的位置是兴趣点模型中的范围

相关问题