2015-11-02 29 views
0

我创建Ruby中的应用程序,我有两个模型类查询在contoller- ROR

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 
+0

我想你已经为蓝本的数据不正确,这可能是你的一些问题的根源。你能举一些数据的例子吗? (例如,餐馆,环境,以及它们之间的关系?) 此外,是否有任何特定的原因,你为什么选择'标题'作为你的主要关键在惯用的'id'? –

+0

是的,我确实回答了这个问题,但是通过阅读这篇文章,您是否正在尝试在用户选择UI上的selected_environment后执行查询? – DustinFisher

+0

是的DustinFisher是正确的 – noob

回答

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

我收到以下SQL lite错误 SQLite3 :: SQLException:no such column:environments.restaurant_id:SELECT“restaurants”。* FROM“restaurants”INNER JOIN“environments”ON“environments”。“restaurant_id”=“restaurants” 。“title”WHERE“environments”。“env_type”IN('casual','outdoor_sitting','romantic') – noob

+0

加入正在拾取不存在的restaurant_id而不是标题 – noob

+0

我更新了您的结构的答案楷模。 – DustinFisher