1

我有一个多态位置模型:

class Location < ActiveRecord::Base
  acts_as_mappable
  before_validation :geocode_address, :on => :create
  belongs_to :locatable, :polymorphic => true
end 

以及引用它的用户模型:

class User < ActiveRecord::Base
  acts_as_mappable :through => :location
  has_one :location, :as => :locatable
end 

在 Rails 控制台中将位置分配给用户的正确方法是什么?当我尝试以下操作时,出现错误:

l = Location.create(:full_address=>'123 maple street, chicago, il')
u = User.create(:username=>'foo') # => ArgumentError: You gave location in :through, but I could not find it on User.

我没有机会将位置分配给用户。

如果我删除 'acts_as_mappable :through => :location' 指令,我可以毫无问题地分配位置:

l = Location.create(:full_address=>'123 maple street, chicago, il')
u = User.create(:username=>'foo')
u.location = l
4

1 回答 1

1

:location 的定义需要在其使用之前:

class User < ActiveRecord::Base
  has_one :location, :as => :locatable
  acts_as_mappable :through => :location
end 
于 2011-02-11T17:20:06.533 回答