在Rails控制台中分配多态的acts_as_mappable模型

时间:2011-02-10 22:25:50

标签: ruby-on-rails-3 geokit rails-console

我有一个多态的位置模型:

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 =&gt; :location'指令,我可以分配一个没有问题的位置:

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

1 个答案:

答案 0 :(得分:1)

定义:位置需要先于其使用:

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