gpt4 book ai didi

ruby - # 的未定义方法 `keys'

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:26 25 4
gpt4 key购买 nike

我有模型order.rb

class Order < ActiveRecord::Base
belongs_to :customer

has_many :products, dependent: :destroy, class_name: 'OrderProduct'
has_many :attributes, dependent: :destroy, class_name: 'OrderAttribute'
has_one :invoice_address, class_name: 'OrderAddress'
has_one :delivery_address, class_name: 'OrderAddress'

validates :number, presence: true
validates :total_amount, presence: true
end

当我运行 rspec 时我收到错误

undefined method `keys' for #<ActiveRecord::Associations::CollectionProxy []>

保存订单时在线。当我注释掉时

    has_many :attributes, dependent: :destroy, class_name: 'OrderAttribute'

它按预期工作。我的 rspec 文件是:

require "spec_helper"

describe Order do
before { @order = Order.new(:number => '132', :total_amount => 123, :paid_amount => 123) }

it { assert_equal true, @order.valid? }

describe "number cannot be empty" do
before { @order.number = nil }
it { assert_equal false, @order.valid? }
end

describe "total_amount cannot be nil" do
before { @order.total_amount = nil }
it { assert_equal false, @order.valid? }
end

describe "can add products" do
before do
@order.save
@order.products.create(:name => 'test', :price => 123, :qty => 1)
end

it { assert_equal 1, @order.products.count }
end

# describe "can add attribute" do
# before do
# @order.save
# @order.attributes.create(:key => 'some_key', :value => '12')
# end

# it { assert_equal 1, @order.attributes.count }
# it { assert_equal 'some_key', @order.attributes.first.key }
# it { assert_equal '12', @order.attributes.first.value }
# end
end

我注释掉订单属性的测试,因为它会产生另一个错误。如何解决?我有 order_comment.rb 文件

class OrderAttribute < ActiveRecord::Base
belongs_to :order
end

这是怎么回事?

最佳答案

重命名 attributes 因为这是导致您出现问题的原因

if you have a has_many called attributes, you can’t access to your object attributes anymore; only the associated objects Original Rails Wiki - additional words

相关链接:

http://reservedwords.herokuapp.com/words/attributes

关于ruby - #<ActiveRecord::Associations::CollectionProxy []> 的未定义方法 `keys',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22513346/

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