2010-03-11 30 views
1

IM試圖做到這一點:Rails的:聯想模型有兩個同類

class Event < ActiveRecord::Base 
    belongs_to :previous_event 
    has_one :event, :as => :previous_event, :foreign_key => "previous_event_id" 
    belongs_to :next_event 
    has_one :event, :as => :next_event, :foreign_key => "next_event_id" 
end 

,因爲我想使用戶能夠重複事件,並在同一時間改變多個迎面而來的事件。我做錯了什麼,還是有另一種做法呢?不知何故,我需要知道上一個和下一個事件,不是嗎?當我在consolewith Event.all[1].previous_event測試,我得到以下錯誤:

NameError: uninitialized constant Event::PreviousEvent 
    from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2199:in `compute_type' 
    from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2195:in `compute_type' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `send' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:156:in `klass' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/belongs_to_association.rb:49:in `find_target' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_proxy.rb:239:in `load_target' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_proxy.rb:112:in `reload' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1250:in `previous_event' 
    from (irb):2 

什麼錯誤嗎?謝謝你的幫助。

回答

0

它應該就是這樣的,沒有必要,因爲它的belongs_to的無論如何。

class Event < ActiveRecord::Base 
    has_one :next_event, :class_name => "Event", :foreign_key => "previous_event_id" 
    has_one :previous_event, :class_name => "Event", :foreign_key => "next_event_id" 
end 

雖然這裏的問題是,你必須手動設置它的下一個和以前的事件。你可能只是有一個next_event和查找上一個(或反之亦然 - 這取決於在你的使用情況更有效)

class Event < ActiveRecord::Base 
    has_one :next_event, :class_name => "Event", :foreign_key => "previous_event_id" 
    def previous_event 
    Event.first(:conditions => ["next_event_id = ?", self.id]) 
    end 
end 
+0

你說得對,我可能甚至不會需要參考先前的事件。並且它在沒有belongs_to的情況下效果很好!謝謝 – 2010-03-12 00:42:46

0

啊,剛剛發現的錯誤,這是做正確的方式:

class Event < ActiveRecord::Base 
    belongs_to :previous_event,:class_name => "Event" 
    has_one :event, :as => :previous_event, :class_name => "Event", :foreign_key => "previous_event_id" 
    belongs_to :next_event,:class_name => "Event" 
    has_one :event, :as => :next_event, :class_name => "Event", :foreign_key => "next_event_id" 
end 

發現here

相關問題