Rails 3.2.8 - 如何进行递归has_one检查?

时间:2012-10-21 22:31:40

标签: ruby-on-rails ruby ruby-on-rails-3

我有以下型号:

class Point < ActiveRecord::Base
 ...

 has_one :next_point, class_name: "Point", foreign_key: "next_point_id"
 belongs_to :previous_point, class_name: "Point", foreign_key: "next_point_id"

 # It should return an array with the next remaining points
 def next_remaining_points
 end

end

如何在next_point为nil之前执行返回next_point的方法?

1 个答案:

答案 0 :(得分:0)

在Ruby代码中有一个简单的递归解决方案,但要注意这可以为每个调用执行数据库查询。使用自定义SQL查询可能会更好。

class Point < ActiveRecord::Base
  ...
  def last_point  # Or some better name
    next_point.try(:last_point) || self
  end