Justin D.
Justin D.

Reputation: 4976

One to many relationships in Rails

I'm having a hard time setting up the basic structure of my databases.

I have products (about 50). Each products is related to one or more place(s).

The basic schema would be this (no relation yet)

Products

id:integer
name:string

Places

id:integer
name:string
content:string

I first tought I could connect places and products by adding place_id to products and has_many belong_to in the controllers, but since a product can have more than one place, I don't know how.

Upvotes: 0

Views: 340

Answers (3)

Andrew France
Andrew France

Reputation: 4879

If a Product has_many Places and a Place has_many Products your association needs to be many-to-many.

There are two ways to do this in Rails, the most recommended is a join model. You explicitly label the relationship between Products and Places. You could call it ProductLocation or Shop or similar, it would look like this:

product_locations:
  product_id
  place_id

class ProductLocation < ActiveRecord::Base
  belongs_to :product
  belongs_to :place
end

class Place < ActiveRecord::Base
  has_many :product_locations
  has_many :products, :through => :product_locations
end

class Product < ActiveRecord::Base
  has_many :product_locations
  has_many :places, :through => :product_locations
end

See http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

Upvotes: 1

Ximik
Ximik

Reputation: 2495

Just use through connection

ProductsPlaces (new table)

product_id
place_id

And in models

class Product < ActiveRecord::Base
  has_many :places, :through => :products_places
end

class Place < ActiveRecord::Base
  has_many :products, :through => :products_places
end

Also there is has_and_belongs_to_many which do in fact the same (with ProductsPlaces table)

class Product < ActiveRecord::Base
  has_and_belongs_to_many :places
end

class Place < ActiveRecord::Base
   has_and_belongs_to_many :products
end

But better use through, because has_and_belongs_to_many will be deprecated.

Upvotes: 1

gmoore
gmoore

Reputation: 5566

It sounds like you want to add product_id to places.

Product has_many Places

Place belongs_to Product

Upvotes: 0

Related Questions