Database rails中的模型关联

Database rails中的模型关联,database,ruby-on-rails-3,model,associations,Database,Ruby On Rails 3,Model,Associations,在我的应用程序中,用户可以创建约会 class User has_many :appointments end class Appointment belongs_to :user end 但是,用户也可以加入其他用户创建的其他约会 有人能推荐一种设置我的模型的方法吗 我一直在通读,找不到正确的关联 我真的很想用rails的方式来实现这一点,而不是对我的应用程序进行黑客攻击 _和_属于_\u会是一条路吗?听起来你可能想用某种模型来描述用户和约会之间的关系: # models/

在我的应用程序中,用户可以创建约会

class User
    has_many :appointments
end

class Appointment
    belongs_to :user
end
但是,用户也可以加入其他用户创建的其他约会

有人能推荐一种设置我的模型的方法吗

我一直在通读,找不到正确的关联

我真的很想用rails的方式来实现这一点,而不是对我的应用程序进行黑客攻击


_和_属于_\u会是一条路吗?

听起来你可能想用某种模型来描述用户和约会之间的关系:

# models/user_appointment.rb
class UserAppointment < ActiveRecord::Base
  belongs_to :user
  belongs_to :appointment
end

# models/appointment.rb
class Appointment < ActiveRecord::Base
  has_many :user_appointments
  has_many :users, :through => :user_appointments
end

# models/user.rb
class User < ActiveRecord::Base
  has_many :user_appointments
  has_many :appointments, :through => :user_appointments
end

听起来不错。只是打字,没有测试——如果我需要调整或澄清任何事情,请告诉我!我应该在模型中创建一些新字段吗?最初在用户中,我有“name”和“email”。虽然约会有“user\u id”和各种约会信息字段。是的,您需要为
user\u约会
表创建数据库迁移,并将
owner\u id
列添加到
约会
表我在“归属于:所有者”处收到错误,:as=>:user'Unknown key:asYou's right--我应该使用
:class\u name
作为
:所属的
。我还应该提到,
:owner
在上面的示例中并没有真正被使用(例如,我没有在
User
中添加一个对等关系来描述
:owned_约会
或类似的东西……但如果需要的话,这很容易做到)
# models/appointment.rb
class Appointment < ActiveRecord::Base
  has_many :user_appointments
  has_many :users, :through => :user_appointments
  belongs_to :owner, :class_name => 'User'
end