2010-09-15 42 views
1

我确定这已经被问过100万次了。我只是搜索得不好。我有以下设置:我有一个有许多事件的讲师。每个活动只有一名讲师(所有者/创建者)。我想添加一个单独的链接以允许其他教师关联,但仍保留原始教师(所有者)。我有一个粗糙的ASCII表示,但我不能为我的生活弄清楚如何在轨道模型中做到这一点。使用has_many和has_one将两个表链接在一起?

   ,-------------------. 
       | 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 ...] 

回答

1

2点为ASCII。

我对Rails一无所知,但是将event表的教师外语引用关闭并将is_primary_instructor位字段添加到关联的事件表会更有意义吗?

+0

感叹。你的权利。我希望避免重组我的数据库。现在最好在推出前进行生产。 – Sukima 2010-09-15 11:56:01

1

同意Shlomo。

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 

所以每个老师都有很多活动,每个活动都有很多老师。但是你必须确定一个指导作为主要指导员。

===== UPDATE =====

要引用主讲师:

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

+0

那么你如何引用primary_instructor? – Sukima 2010-09-15 21:56:46

+0

我更新了答案,以显示找到主要教师的方式。希望适合你。 – PeterWong 2010-09-16 02:27:16