Rickmasta
Rickmasta

Reputation: 449

Associate one model to two different models?

Hey guys. I'm trying to build this Picture Battle site, (where you chose the picture you prefer) and I had two models. Pictures, and Battles.

So Each Picture has_many Battles, but Each Battle belongs to two pictures. How do I associate it.. I was thinking something like "belongs_to_many" but apparently that doesn't exist.

Upvotes: 0

Views: 257

Answers (2)

Andrei S
Andrei S

Reputation: 6516

from what i see this could be easily done by using a has_and_belongs_to_many association

You should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, which is probably the case, it may be simpler to set up a has_and_belongs_to_many relationship

here's how you do the HABTM:

class Picture < ActiveRecord::Base
  has_and_belongs_to_many :battles
end

and

class Battle < ActiveRecord::Base
  has_and_belongs_to_many :pictures
end

then you can call picture.battles and battle.pictures

you will also need to create a new migration that looks like this

class CreateBattlesPicturesJoinTable < ActiveRecord::Migration
  def self.up
    create_table :battles_pictures, :id => false do |t|
      t.integer :battle_id
      t.integer :picture_id
    end
  end

  def self.down
    drop_table :battles_pictures
  end
end

more info here

Upvotes: 2

Syed Aslam
Syed Aslam

Reputation: 8807

It is a many-to-many association. You can achieve it through a join model. Check has_many in the API docs

Upvotes: 0

Related Questions