Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 控制器中有多种型号,rails 4有哪些良好的实践?_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 控制器中有多种型号,rails 4有哪些良好的实践?

Ruby on rails 控制器中有多种型号,rails 4有哪些良好的实践?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我目前正在使用RubyonRails开发一个web应用程序。我有一个控制器,它可以获得两个参数:城市和子类别。 我有一个名为InterestPoint的模型,它属于子类别和城市 利用我在网上读到的内容,我最终列出了所有与城市和类别相匹配的兴趣点: class SubCategoryController < ApplicationController def index @city = City.where(route_str: params[:city]).first

我目前正在使用RubyonRails开发一个web应用程序。我有一个控制器,它可以获得两个参数:城市和子类别。 我有一个名为
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
它运行得很好,但RubyMine(我的IDE)一直告诉我这是一个糟糕的做法:每个控制器只能使用一个模型

所以,我的问题是,为什么这是一个不好的做法,我如何才能做到“正确的方式”

我基于khaled_gomaa one的回答:

步骤1,从子类别控制器移动到兴趣点控制器,因为这是页面的主题

步骤2,在我的兴趣点模型中创建了作用域:

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,将索引操作添加到我的兴趣点控制器:

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

根据我从你那里得到的

  • 此控制器应为感兴趣的点控制器作为其主控制器 功能是显示所有兴趣点的列表
  • 兴趣点模型应包含用于 检索位于给定城市和城市中的所有兴趣点 在给定的子类别下,您只需在控制器中调用它
  • 所以你会有这样的东西

    class InterestPointsController < ApplicationController
    
      def index
        @interest_point = InterestPoint.located(params[:city]).categorized(params[:sub_category])
      end
    end
    
    类兴趣点控制器

    其中位于和分类的是兴趣点模型中的作用域

    控制器子类别的名称是什么,因为它是我的URL中的最后一个参数。这也不好吗?我只需要了解整个情况,就可以帮助你理解为什么这不是正确的方法。好的,你的url是这样的/city/sub_分类的,对吗?是的,我用路线编辑了我的帖子。这个页面应该只显示兴趣点?或者将显示与城市和子类别相关的内容。我的意思是,页面的主要英雄是什么?是子类别还是兴趣点,因为我觉得兴趣点是该操作的主要目标?最后一个小问题,既然没有更多的城市和子类别,我现在如何从控制器获取城市和子类别对象?要在视图中显示他们的姓名吗?如果您说InterestPoint.includes(:city,:sub_category)。locat。。。。。。您将拥有城市和子类别,您可以使用其中任何一个
    def index
       @interest_points = InterestPoint.by_location(params[:city]).by_category(params[:sub_category]).load
    end
    
    class InterestPointsController < ApplicationController
    
      def index
        @interest_point = InterestPoint.located(params[:city]).categorized(params[:sub_category])
      end
    end