1

希望这会很简单。但我现在已经狩猎了几个小时,似乎无法让它发挥作用。我有多个地址的用户,我正在尝试使用 Geocoder gem 通过邮政编码搜索显示这些用户,我的代码与 Geocoder Railscast 中的代码非常相似。

这是我的控制器尝试 1 并返回“未定义的方法‘地址’”

def index
  if params[:search].present?
    @profiles = Profile.Addresses.near(params[:search], 25, :order => :distance)
    @title = "Therapists Near " + :search
  else
  @profiles = Profile.all
  @title = "Everyone"
  end
end

这是第 2 次尝试,这将返回“未初始化的常量 ProfilesController::Addresses”(我不知道 Profile.where 位是否有效,但它甚至没有到达那部分......)

class ProfilesController < ApplicationController

  def index
    if params[:search].present?
      addresses = Addresses.near(params[:search], 25, :order => :distance)
      @profiles = Profile.where(:id => addresses.id)
      @title = "Therapists Near " + :search
    else
    @profiles = Profile.all
    @title = "Everyone"
    end
  end

这是我的模型:

class Profile < ActiveRecord::Base
  has_many :addresses, :dependent => :destroy
  accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a[:street].blank? }, :allow_destroy => true

class Address < ActiveRecord::Base
  belongs_to :profile
  geocoded_by :street
  after_validation :geocode, :if => :street_changed?

非常感谢您的观看!

4

3 回答 3

1

此外,您可以更改为以下内容以获取所有配置文件:

addresses = Address.near(params[:search], 25, :order => :distance)

@profiles = addresses.map{ |ad| ad.profile }.uniq unless addresses.nil?

如果有匹配的地址,则从每个地址中查找配置文件。

于 2012-01-15T07:46:45.580 回答
0

我发现我无法对接受的答案进行分页。所以我变得很肮脏:

addresses = Address.near(params[:search], 25, :order => :distance)
locations_id_array = []  
addresses.each do |address| 
  addresses_id_array << address.id
end  
@profiles  = Profile.where(:address_id => addresses_id_array).paginate(:page => params[:page],  :per_page => 5).order('name DESC')

如果有人有更好的、可扩展的方式来做到这一点(最好是使用示波器),我很想听听。

于 2013-01-02T05:09:13.007 回答
0

对于数字 2,您必须从 更改Addresses.near(params[:search], 25, :order => :distance)Address.near(params[:search], 25, :order => :distance)

于 2012-01-15T07:01:23.540 回答