1

私はこれをやろうとしています:

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

ユーザーがイベントを繰り返し、複数の今後のイベントを同時に変更できるようにしたいからです。私は何を間違っていますか、またはこれを行う別の方法はありますか? どういうわけか、前のイベントと次のイベントについて知る必要がありますね。これを consolewithEvent.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

ここで何がうまくいかないのですか?あなたの助けに感謝します。

4

2 に答える 2

0

とにかく循環するので、begs_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
于 2010-03-11T21:32:53.383 に答える
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

ここで見つけた

于 2010-03-11T21:24:25.950 に答える