1

希望这会很简单。但我现在已经追捕了几个小时,似乎无法让这个工作。我有拥有多个地址的用户,我尝试使用Geocoder gem通过邮政编码搜索来显示这些用户,我的代码与Geocoder Railscast中的内容非常相似。Rails模型关联问题

这里是我的控制器尝试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 ::地址’(我不知道,如果档案。凡位的工作,但它甚至没有获得该部分...)

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? 

非常感谢您的关注!

回答

1

另外,您可以更改为以下来获取所有配置文件:

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

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

如果有匹配的地址,然后找到每个地址的配置文件。

+0

这工作几乎完美。必须切换.blank?去.nil? – Robert 2012-01-15 08:02:20

+0

你找回一个无法分页的数组 – Will 2013-01-02 04:48:21

0

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

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') 

如果任何人有一个更好的,可扩展的方式做到这一点(最好用示波器)我很乐意听到它。