Search code examples
ruby-on-railsjoinruby-on-rails-4model-associations

Retrieving information from Rails 4 associated models


What is the most efficient way for retrieving all unique venues with a specified set of features?

In the controller, I have:

@venues = Venue.all
@venues = @venues.features.where('feature.id == ' 1).distinct

Here's how my models are defined:

class Neighborhood < ActiveRecord::Base
  has_many :venues
end

class Venue < ActiveRecord::Base
  belongs_to :neighborhood
  has_many :features
end

class FeatureType < ActiveRecord::Base
  has_many :features  
end

class Feature < ActiveRecord::Base
  belongs_to :venue
  belongs_to :feature_type
end

Solution

  • Just think about this using English. If a Venue has many Features and you ask "What is the Id of the Feature?" the response is going to be: "There are many Features, which one?"

    The :has_many association gives you the following method: venure.features. That gives you all the of the "many" associated features. To get the Id of just one, you could do something like: venue.features.first.id.