#47 Two Many-to-Many

There are two different ways to set up a many-to-many association in Rails. In this episode you will see how to implement both ways along with some tips on choosing the right one for your project.

has_and_belongs_to_many
# in migration
def self.up
  create_table 'categories_products', :id => false do |t|
    t.column :category_id, :integer
    t.column :product_id, :integer
  end
end

# models/product.rb
has_and_belongs_to_many :categories

# models/category.rb
has_and_belongs_to_many :products

has_many :through
# models/categorization.rb
belongs_to :product
belongs_to :category

# models/product.rb
has_many :categorizations
has_many :categories, :through => :categorizations

# models/category.rb
has_many :categorizations
has_many :products, :through => :categorizations

你可能感兴趣的:(java,UP,Rails)