1

我确定这已经被问了一百万次了。我只是没有很好地搜索。我有以下设置:我有一个有很多事件的讲师。每个活动只有一名讲师(所有者/创建者)。我想添加一个单独的链接以允许关联其他讲师,但仍保留原始讲师(所有者)。我有一个粗略的 ASCII 表示,但我一生都无法弄清楚如何在 rails 模型中做到这一点。

                ,-------------------.
                | other_instructors |
                |-------------------|
                | event_id          |-------------.
,---------------| instructor_id     |             |
|               `-------------------'             |
|   ,---------------------.                       |
`->>| instructor          |<--.                   |
    |---------------------|   |   ,------------.  |
    | name                |   |   | event      |<-'
    | email               |   |   |------------|
    | office              |   |   | title      |
    | phone               |   |   | location   |
    | admin?              |   |   | benefit    |
    | notify_recipient?   |   |   | notes      |
    | new_user?           |   |   | start_time |
    | (acts_as_authentic) |   |   | end_time   |
    `---------------------'   |   | live_in?   |
                              `---| instructor |
                                  `------------'
@instructor.events = [... array of events ...]
@associated_events = [... array of events associated but not owned via other_instructors table ...]
@event.instructor = ... One Instructor ...
@event.other_instructors = [... array of other instructors ...]
4

2 回答 2

1

ASCII 2 分。

我对 Rails 一无所知,但是将讲师的外部参考从event表中删除并在关联的事件表中添加一个is_primary_instructor位字段会更有意义吗?

于 2010-09-15T02:21:46.557 回答
1

同意什洛莫。

class Instructor < ActiveRecord::Base
  has_many :instruct_events
  has_many events, :through => :instruct_events
end

class InstructEvent < ActiveRecord::Base
  belongs_to :instructor
  belongs_to :event
end

class Event < ActiveRecord::Base
  has_many :instruct_events
  has_many :instructors, :through => :instruct_events
end

class CreateInstructors < ActiveRecord::Migration
  def self.up
    create_table :instructors do |t|
      # name, email, etc
      t.timestamps
    end
  end
end

class CreateInstructEvents < ActiveRecord::Migration
  def self.up
    create_table :instruct_events do |t|
      t.integer :instructor_id
      t.integer :event_id

      t.boolean :is_primary_instructor
      t.timestamps
    end
  end
end

class CreateEvents < ActiveRecord::Migration
  def self.up
    create_table :events do |t|
      # title, location, etc
      t.timestamps
    end
  end
end

所以每个教练都有很多活动,每个活动都有很多教练。但是您必须确定一位指导员作为主要指导员。

===== 更新 =====

参考主要讲师:

class InstructEvent
  # add this:
  named_scope :primary, :conditions => { :is_primary_instructor => true }
end

给定一个事件,找到该事件的主要讲师:

event.instruct_events.primary.instructor

给定一个讲师,找出该讲师是主要的事件:

instructor.instruct_events.primary.event

也许你可以给 InstructEvents 类起一个更好的名字。

而且我也希望看到更多漂亮的解决方案:D

于 2010-09-15T02:37:08.263 回答