2010-09-15 43 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