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

如果任何人有一個更好的,可擴展的方式做到這一點(最好用示波器)我很樂意聽到它。