Reputation: 43
I am creating an application in Ruby and I have two model classes
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
I am trying to query two tables in the controller- to return restaurants with specific environments.
@restaurants = Restaurant.joins('INNER JOIN environments ON restaurants.title=environments.title').where('environments.env_type'=> @selected_environment)
NOTE: @selected_environment is a hash contained list of environments. Environments table has a list of environment and restaurant pairs(there can be more than one restaurant). I know the query above is not correct to achieve my goal. Is there a way i can get this done?
controller method:
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
Upvotes: 0
Views: 70
Reputation: 396
For your models you want to do this:
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
Try structuring your query like this:
Restaurant.joins(:environments).where(environments: { env_type: @selected_environments.values })
Upvotes: 1