我创建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
我想你已经为蓝本的数据不正确,这可能是你的一些问题的根源。你能举一些数据的例子吗? (例如,餐馆,环境,以及它们之间的关系?) 此外,是否有任何特定的原因,你为什么选择'标题'作为你的主要关键在惯用的'id'? –
是的,我确实回答了这个问题,但是通过阅读这篇文章,您是否正在尝试在用户选择UI上的selected_environment后执行查询? – DustinFisher
是的DustinFisher是正确的 – noob