代码之家  ›  专栏  ›  技术社区  ›  Patrick Oscity

Rails:将模型与同类的两个模型相关联

  •  1
  • Patrick Oscity  · 技术社区  · 16 年前

    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
    

    因为我想使用户能够重复事件并同时更改多个即将到来的事件。我做错了什么,还是有别的方法?不知何故,我需要知道上一个和下一个事件,不是吗?当我在控制台上用 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
    

    2 回复  |  直到 16 年前
        1
  •  0
  •   Will    16 年前

    它应该是这样工作的,因为它是循环的,所以没有必要使用它。

    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
    

    但这里的问题是,您必须手动设置它的下一个和上一个事件。您可以只拥有下一个事件并查找上一个事件(反之亦然-取决于在您的用例中哪个更有效)

    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
    
        2
  •  0
  •   Patrick Oscity    16 年前

    啊,刚刚发现错误,这是正确的方法:

    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

    推荐文章