Mysql 在rails项目中映射旧数据库列

Mysql 在rails项目中映射旧数据库列,mysql,ruby-on-rails,ruby,activerecord,models,Mysql,Ruby On Rails,Ruby,Activerecord,Models,我们正在为一个已经存在的数据库创建一个rails应用程序。我们需要将一些数据库表映射到一起 假设我们有三个表:事件、事件组和事件组。 有一些事件,有一些组,每个事件可以分配给一个或多个组 如何在rails中对这种关系建模 例如: 现有表格: event ID name -------------------- 3 dinner 4 sport 5 anniversary 6 birthday

我们正在为一个已经存在的数据库创建一个rails应用程序。我们需要将一些数据库表映射到一起

假设我们有三个表:事件、事件组和事件组。
有一些事件,有一些组,每个事件可以分配给一个或多个组

如何在rails中对这种关系建模

例如:

现有表格:

event ID name -------------------- 3 dinner 4 sport 5 anniversary 6 birthday event_groups ID name -------------------- 1 work 2 friends 3 family event_to_groups event_id event_groups -------------------- 3 2 3 3 4 1 4 2 4 3 5 3 6 2 事件 身份证名称 -------------------- 3晚餐 4运动 五周年纪念 6岁生日 事件组 身份证名称 -------------------- 1工作 两个朋友 3个家庭 事件组到事件组 事件标识事件组 -------------------- 3 2 3 3 4 1 4 2 4 3 5 3 6 2 类事件如何从事件模型中检索属于事件的组名?谢谢

有几件事-首先,ActiveRecord模型应该是单数的,而不是复数的。另外,我假设您的意思是组模型的表是“event_groups”,而不是“groups”

试试这个:

class Event < ActiveRecord::Base
  set_table_name 'events'
  has_many :event_to_groups
  has_many :groups, :through => :event_to_groups
end

class Group < ActiveRecord::Base
  set_table_name 'event_groups'
  has_many :event_to_groups
  has_many :events, :through => :event_to_groups
end

class EventToGroup < ActiveRecord::Base
  set_table_name 'event_to_groups'
  belongs_to :event
  belongs_to :group, :foreign_key => 'event_groups'
end
编辑:确认,这些关系应该有很多,而不仅仅是很多。我用MongoMapper太多了

class Groups < ActiveRecord::Base set_table_name 'groups' end class EventToGroups < ActiveRecord::Base set_table_name 'event_to_groups' end
class Event < ActiveRecord::Base
  set_table_name 'events'
  has_many :event_to_groups
  has_many :groups, :through => :event_to_groups
end

class Group < ActiveRecord::Base
  set_table_name 'event_groups'
  has_many :event_to_groups
  has_many :events, :through => :event_to_groups
end

class EventToGroup < ActiveRecord::Base
  set_table_name 'event_to_groups'
  belongs_to :event
  belongs_to :group, :foreign_key => 'event_groups'
end
@event = Event.find(5)
@groups = event.groups