Rails:将模型与其中两种相关联

时间:2010-03-11 21:11:10

标签: ruby-on-rails associations has-one

我试图这样做:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
相关问题