如何从has_and_belongs_to_many模型关系访问表

时间:2011-03-07 05:30:48

标签: ruby-on-rails activerecord join

我有一个模型作为名为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

CELEBRATIONS表中的角色是:所有者,经理或朋友

我希望USERS记录一个角色为FRIEND的BOARD。

我似乎错过了什么。

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

任何人都可以直接指出我吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您的模特中的关系错误。 对于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.