查询控制器 - ROR

时间:2015-11-02 18:35:07

标签: ruby-on-rails ruby

我在Ruby中创建一个应用程序,我有两个模型类

class Restaurant < ActiveRecord::Base
    attr_accessible :title, :cuisine, :price_range, :environment
    self.primary_key = 'title'
     has_many :environments
    end
end


class Environment < ActiveRecord::Base
    attr_accessible :title, :type
     belongs_to :restaurants,foreign_key: 'title'

end

我正在尝试查询控制器中的两个表 - 以返回具有特定环境的餐馆。

@restaurants = Restaurant.joins('INNER JOIN environments ON restaurants.title=environments.title').where('environments.env_type'=> @selected_environment)

注意:@selected_environment是包含哈希的环境列表。环境表有一个环境和餐馆对的列表(可以有多个餐厅)。 我知道上面的查询是不正确的,以实现我的目标。我有办法完成这项工作吗?

控制器方法:

  def index

         # can later be moved to the Restaurant model
         ordering = {:title => :asc}
         @all_environments = Restaurant.all_environments

         @selected_environments = params[:environments] || session[:environments] || {}
         if @selected_environments == {}
           @selected_environments = Hash[@all_environments.map {|environment| [environment, environment]}]
         end
         if params[:environments] != session[:environments]
           session[:environments] = @selected_environments
           redirect_to :environments => @selected_environments and return
         end
        @restaurants = Restaurant.joins(:environments).where(environments:{env_type: @selected_environments.keys })

  end

1 个答案:

答案 0 :(得分:1)

对于您的模型,您希望这样做:

class Restaurant < ActiveRecord::Base
  attr_accessible :title, :cuisine, :price_range, :environment
  self.primary_key = 'title'
  has_many :environments, :foreign_key => 'title', :primary_key => 'title'
end


class Environment < ActiveRecord::Base
  attr_accessible :title, :type
  belongs_to :restaurants, foreign_key: 'title'
end

尝试按以下方式构建查询:

Restaurant.joins(:environments).where(environments: { env_type: @selected_environments.values })