gpt4 book ai didi

ruby-on-rails - Rails 3 多态关联引发 NameError

转载 作者:行者123 更新时间:2023-12-04 06:34:43 25 4
gpt4 key购买 nike

我有以下两个模型:

class FuzzyDate < ActiveRecord::Base
belongs_to :fuzzy_dateable, :polymorphic => true
end

class Device < ActiveRecord::Base
has_one :received_date, :as => :fuzzy_dateable
end

具有以下架构:

  create_table "devices", :force => true do |t|
t.string "meid"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "fuzzy_dates", :force => true do |t|
t.date "date"
t.integer "fuzz"
t.integer "fuzzy_dateable_id"
t.string "fuzzy_dateable_type"
t.datetime "created_at"
t.datetime "updated_at"
end

让我们启动控制台,好吗?

>> d = Device.create(:meid => "A")
=> #<Device id: 1, meid: "A", created_at: "2010-12-16 06:52:55", updated_at: "2010-12-16 06:52:55">
>> fd = FuzzyDate.create(:date => Date.today, :fuzz => 3)
=> #<FuzzyDate id: 1, date: "2010-12-15", fuzz: 3, fuzzy_dateable_id: nil, fuzzy_dateable_type: nil, created_at: "2010-12-16 06:53:04", updated_at: "2010-12-16 06:53:04">
>> fd.fuzzy_dateable = d
=> #<Device id: 1, meid: "A", created_at: "2010-12-16 06:52:55", updated_at: "2010-12-16 06:52:55">
>> fd
=> #<FuzzyDate id: 1, date: "2010-12-15", fuzz: 3, fuzzy_dateable_id: 1, fuzzy_dateable_type: "Device", created_at: "2010-12-16 06:53:04", updated_at: "2010-12-16 06:53:04">

好的,到目前为止,还不错。让我们从另一个方向:

>> d.received_date
NameError: uninitialized constant Device::ReceivedDate
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/base.rb:1199:in `compute_type'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/reflection.rb:162:in `send'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/reflection.rb:162:in `klass'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/reflection.rb:198:in `quoted_table_name'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/has_one_association.rb:97:in `construct_sql'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations/has_one_association.rb:7:in `initialize'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations.rb:1450:in `new'
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.3/lib/active_record/associations.rb:1450:in `received_date'
from (irb):5
>>

呸!我已经做了很多 Googleing,我发现的答案都是错误地使用复数模型名称,这里不是这种情况。我花了几个晚上的时间来反对这个问题,所以非常感谢任何指导。

最佳答案

这里的问题是,在您的 Device 模型中,您将关联命名为 :received_date 并且默认情况下它将查找 ReceivedDate 模型,除非您另有说明。

我会说您可以从这些解决方案中选择任何一种。

没有。 1

class Device < ActiveRecord::Base
has_one :received_date, :as => :fuzzy_dateable, :class_name => "FuzzyDate"
end

没有。 2

class Device < ActiveRecord::Base
has_one :fuzzy_date, :as => :fuzzy_dateable
end

关于ruby-on-rails - Rails 3 多态关联引发 NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4458443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com