hugalves
hugalves

Reputation: 373

Handling relationship with ActiveRecord

I have two models to make a relationship between them, where I need to access stores of a radar and the radars of a store. A radar could monitoring zero or many stores. A store could belong to zero, one or many radars.

I would like to have something like this:

store = Store.first
store.radars #all radars of the store location

And the opposite too:

radar = Radar.first
radar.stores #all stores of the radar location

My classes:

class Store < ActiveRecord::Base
  attr_accessible :title, :description, :user, :store_group, :city, 
                  :neighborhood, :sublocality, :post_code, :route,
                  :street_number, :latitude, :longitude
end

class Radar < ActiveRecord::Base
  attr_accessible :name, :radius, :latitude, :longitude, :user
end

How can I create a migration to handle this?

Upvotes: 0

Views: 47

Answers (1)

Doon
Doon

Reputation: 20232

What you are looking for is a has_and_belongs_to_many association between radars and stores. The question you need to ask your self is will there ever be any attributes on the the joining between the two models? If so you might considering using an explicit join model, that will hold those attributes. In that case you would be looking at a has_many :through association.

see http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association for information on the HABTM association.

your migration for a HABTM would be something like this.

class CreateRadarStores < ActiveRecord::Migration

 create_table :radars_stores, :id => false do |t|
      t.belongs_to :radar
      t.belongs_to :store
    end
end

The order of the table name is important, since by default rails creates it in alphabetical order of the models.

Your models would need to be updated to include the HABTM

class Store < ActiveRecord::Base
 has_and_belongs_to_many :radars
  ....
end

class Radar < ActiveRecord::Base
 has_and_belongs_to_many :stores
 ....
end

or if using a has many :through look here http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Building that join model would be up to you depending upon attributes reuqired.

Upvotes: 1

Related Questions