2012-01-27 73 views
0

我一直在尋找其他問題/答案,但找不到任何有幫助的東西。我有userseventsstatic_events。我現在想介紹一個scheduleusers保存兩種不同類型的「事件」has_many:通過混淆

我越來越掛在組織關聯。具體將eventsstatic_events與特定的:foreign_key關聯以創建schedule。這是我的第一個應用程序,所以事情還是有點新的。一如既往,任何幫助將不勝感激。以下是我迄今爲止:

型號:

class User < ActiveRecord::Base 
    has_many :events, :through => :schedules, :source => "followed_id" 
    has_many :static_events, :through => :schedules, :source => "followed_id" 
end 

class Event < ActiveRecord::Base 
    belongs_to :users 
    belongs_to :schedules, :foreign_key => "followed_id" 
end 

class StaticEvent < ActiveRecord::Base 
    belongs_to :users 
    belongs_to :schedules, :foreign_key => "followed_id" 
end 

class Schedule < ActiveRecord::Base 
    belongs_to :users 
    has_many :events 
    has_many :static_events 
end 

數據架構:

create_table "schedules", 
t.integer "followed_id" 
end 

create_table "users", 
    t.string "name" 
    t.string "email" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

create_table "events", 
    t.string "content" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    #several more fields left out for brevity 
end 

create_table "static_events", 
    t.string "content" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    #several more fields left out for brevity 
end 

我要對這個以最有效的方式?

回答

1

你的代碼沒問題。但是,目前尚不清楚爲什麼你有兩種不同的型號EventStaticEvent。在你的移植中,他們似乎有相同的字段。這似乎是single-table inheritance的好例子。在那種情況下你Event模式將保持不變,但StaticEvent應該是這樣的:

class StaticEvent < Event 
    # ... 
end 

Event,而不是直接從ActiveRecord::Base繼承。這意味着它獲得了所有Event的行爲,但您也可以只定義特定於StaticEvent的方法和變量。

對於單表繼承,您將不具有static_events表,但您的events表將具有附加字符串字段type。其餘部分將由Rails來完成。

然而,如果StaticEvent沒有從除Event不同的任何方法或變量「這是一個靜態的,」你不認爲你有更多的在未來,它會更有意義爲兩者使用Event並給它一個帶有布爾類型的is_static字段。在這種情況下,您Schedule模型是這樣的:

class Schedule < ActiveRecord::Base 
    # ... 

    has_many :events,  :conditions => { :is_static => false } 

    has_many :static_events, :conditions => { :is_static => true }, 
          :class_name => 'Event' 
end 

這樣每個協會都有自己的名字(eventsstatic_events),但它們指的是同一型號(:class_name => 'Event')。唯一的區別是條件,它指定其中Event記錄是該關聯的一部分。這也可以讓你免費做Schedule.static_events.create ...Schedule.static_events.where(...).first等。

而且最後,你說你「現在要爲大家介紹的時間表,爲用戶節省了兩種不同類型的‘事件’。」如果這是你創建的Schedule模塊,你應該簡單地丟棄Schedule唯一原因模型並直接在User上定義上述關聯。除非它有自己的屬性和/或方法,否則不需要額外的Schedule模型。

+0

約旦,我的錯誤 - 我更新了代碼,他們確實有幾個不同的領域。這就是說,我認爲單表繼承仍然是一條可行的路。除此之外,在':foreign_key'上用''用戶'加入'Event'和'StaticEvent'確定並且不會引起任何問題? – Alekx 2012-01-27 03:55:57

+0

'Schedule'的用途是什麼?這是否意味着它是一個獨立的類,或者它僅僅是用戶和他們保存的事件之間的映射(在這種情況下,「Scheduling」或「Attending」可能是更好的名稱)。 – 2012-01-27 04:56:50

+0

好的電話,'出席'是一個更好的名字。它意味着用戶和他們保存的事件之間的映射。但是在思考之後,我需要將'Event'和'StaticEvent'作爲獨立的模型,因爲它們會有太多不同的信息。還有可能需要創建其他模型並添加到「參加」。鑑於此,我的原始代碼/邏輯是否仍然適用,將'Schedule'的名稱更改爲'Attending'? – Alekx 2012-01-27 16:22:43