2012-01-10 65 views
0

举个例子,我有以下型号:Rails的查找通过协会,地点

class Location < ActiveRecord::Base 
    attr_accessible :name, :full_address, :latitude, :longitude, :attr1 

    geocoded_by :full_address 
    has_many :stores 
    after_validation :geocode, :if => :full_address_changed? 
end 

和:

class Store < ActiveRecord::Base 
    attr_accessible :attr2, :attr3 
    belongs_to :location 
end 

我希望能够做的所有存储了搜索的是:

  1. 都在附近(在位置模型中使用地理编码)
  2. 遇到一些crite ria on位置模型中的attr1
  3. 符合Store模型中attr2,attr3的一些条件。

我应该怎么办?

+0

为什么地点与商店有'has_many'关系?难道不是相反吗?如苹果商店的'has_many'位置。除非某个地点是商场或某物,否则我猜这里只有一家商店? – Batkins 2012-01-10 04:16:07

+0

对不起,这个例子有点误导。请在下面看到我对你的答案的解释。 – 2012-01-10 06:30:04

回答

1

我还在疑惑的关系设置...但说你有一个类似的设置我上面提到:

class Store < ActiveRecord::Base 
    attr_accessible :attr2, :attr3 
    has_many :locations 
end 

class Location < ActiveRecord::Base 
    attr_accessible :name, :full_address, :latitude, :longitude, :attr1 

    geocoded_by :full_address 
    belongs_to :store 
    after_validation :geocode, :if => :full_address_changed? 
end 

你可以做这样的事情......

locations = Location.near(current_location.to_s, 20).where(:attr1 => 'a value') 
stores_that_match = locations.find_all {|loc| loc.try(:store).try(:attr2) == 'value2' && loc.try(:store).try(:attr3) == 'value3' }.map(&:store) 

这就是说,最后一部分将在上面提供的代码中使用ruby进行缩小。如果您想要在关联模型上缩小标准,因为您只是在讨论仅使用查询,您可能不得不使用ActiveRecord's find_by_sql method并手动写出查询。

+0

对不起,我意识到我的例子有点混乱。位置意味着像高尔夫乡村俱乐部,这可能会或可能不会有多个球场(在我的示例中为商店)。 在这个例子中,一个乡村俱乐部的所有课程都有一些类似的属性(地点,俱乐部评级等),但是它们有一些独特的属性。 – 2012-01-10 05:55:19

+0

我可能最终会按照您的建议做,并且只是在每个商店中重复存储经纬度,尽管在一个位置可能有多个商店。 – 2012-01-10 06:01:12