使用where子句查找后代 - Rails 3.0和Ancestry

时间:2012-02-04 15:43:14

标签: ruby-on-rails model parent-child

如何使用where子句查找表中作为另一条记录后代的记录(仅从数据库中获取这些记录)?

我们说我有一棵有地点的树。根位置是国家,下一级别的位置是州,子节点是城市。我怎样才能使用where子句找到某个州的城市呢?

我打算检查一下这些城市'祖先的字符串包括州的祖先字符串,但我无法弄清楚如何做到这一点。

2 个答案:

答案 0 :(得分:1)

假设您有一个名为“locations”的表,您可以使用此位置表创建3个不同的模型:

class Country < ActiveRecord::Base
  set_table_name 'locations'
  has_many :states, :class_name => 'State', foreign_key => "parent_id"
end

class State < ActiveRecord::Base
  set_table_name 'locations'
  has_many :cities, :class_name => 'City', foreign_key => "parent_id"
  belongs_to :parent, :class_name => "Country"
end

class City < ActiveRecord::Base
  set_table_name 'locations'
  belongs_to :parent, :class_name => "State"
end

现在你可以使用像

这样的东西
countries = Country.find(:all, :conditions => {:parent_id => nil } )

因为国家是'根元素',所以他们没有父母。 对于每个国家,你可以通过类似的方式找到州,比如说“美国”的id为1,其状态可以通过以下方式找到:

states = State.find(:all, :conditions => {:parent_id => 1 } )

或者如果你已经将美国放在变量中

usa.states

有关:class_name:foreign_key以及示例中使用的其他has_many选项的详细信息,请参阅Rails Association guide

注意:希望我没有犯过太多错误,但我做了类似的菜单,子菜单及其项目。

Note2 :当然,如果您为国家,州和城市使用3个表格会更简单。然后你可以使用直接的关联。

答案 1 :(得分:0)

使用Ancestry生成的范围,例如children_of(node),您可以在其中提供州的ID。