Rails中的模型关联问题

时间:2012-01-15 06:00:49

标签: ruby-on-rails ruby-on-rails-3.1 nested-attributes rails-geocoder

希望这很简单。但我现在已经猎了几个小时,似乎无法让它发挥作用。我有多个地址的用户,我正在尝试使用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?

非常感谢您一起来看看!

3 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

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

答案 2 :(得分: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')

如果有人有更好的,可扩展的方式(最好有范围),我很乐意听到它。