chell
chell

Reputation: 7866

How to access a table from a has_and_belongs_to_many model relationship

I have a model that acts as a join table called CELEBRATIONS.

CELBERATION
has_and_belongs_to_many :users
belongs_to :board

 create_table :celebrations do |t|
      t.column :board_id,        :int, :null => false
      t.column :user_id,         :int, :null => false 
      t.column :role,            :string, :null => false 
      t.column :token,           :string
      t.timestamps
      end


USER
has_many :celebrations

Board
has_many :celebrations

The Roles in the CELEBRATIONS TABLE ARE: OWNER, MANAGER, OR FRIEND

I would like the USERS records for a BOARD where the role is FRIEND.

I seem to be missing something.

 @invited_friends = User.find(:all, :include => :celebrations, :conditions => ["board_id = ?, role = ?", @board.id, "FRIEND"]) 

could anyone point me in the right direct? Thank you in advance.

Upvotes: 1

Views: 453

Answers (1)

Ashish
Ashish

Reputation: 5791

You are having the wrong relationship in your models. For HABTM,

CELBERATION
has_and_belongs_to_many :users

USER
has_and_belongs_to_many :celebrations


And one more table celebrations_users with user_id, celebration_id columns.
Put the role column in users table.

Upvotes: 1

Related Questions