gpt4 book ai didi

ruby-on-rails - ActiveRecord::UnknownAttributeError in UserController#create

转载 作者:行者123 更新时间:2023-12-04 03:45:52 24 4
gpt4 key购买 nike

我从学习 Rails 开始,为此我开始开发一个具有嵌套属性的运输应用程序。基本上我有模型 UserBoxBoxKind 表,在 BoxKind 之间有 HABTM >.

用户模型

class User < ActiveRecord::Base
has_many :boxes
accepts_nested_attributes_for :boxes
end

盒子模型

class Box < ActiveRecord::Base    
belongs_to :user, :foreign_key => "user_id"
accepts_nested_attributes_for :user

has_and_belongs_to_many :kinds, join_table: :boxes_kinds
accepts_nested_attributes_for :kinds
end

亲切模型

class Kind < ActiveRecord::Base
has_and_belongs_to_many :boxes, join_table: :boxes_kinds
end

当我尝试向数据库中添加新记录时,我收到了一个unknown attribute: box_id 错误。这让我有点困惑,因此我向名为 ref_noBox 模型添加了自定义主键。

我哪里错了?

更新 正如@NitinVerma 所要求的,另外还有控制台日志:

Started POST "/user" for 127.0.0.1 at 2014-08-18 19:27:11 +1000
Processing by UserController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xt5OvI9hfU98rHQ0fGb5NDui1lRg0Bned8+03Hurr1Y=", "user"=>{"name"=>"Mark", "email"=>"mark@abc.com", "address"=>"Some address ", "postcode"=>"1928", "tel_no"=>"0394884994", "state"=>"VIC", "boxes_attributes"=>{"0"=>{"ref_no"=>"1005", "quantity"=>"2", "kinds_attributes"=>{"1408354027248"=>{"big"=>"2", "small"=>"", "odd"=>"", "trunck"=>"", "_destroy"=>"false"}, "0"=>{"big"=>"", "small"=>"", "_destroy"=>"1"}}, "collected_at(1i)"=>"2012", "collected_at(2i)"=>"8", "collected_at(3i)"=>"18", "collected_at(4i)"=>"08", "collected_at(5i)"=>"59", "destination_country"=>"UK", "destination_country_address"=>"Regency Street 18", "shipped"=>"1", "shipped_at(1i)"=>"2014", "shipped_at(2i)"=>"8", "shipped_at(3i)"=>"18", "shipped_at(4i)"=>"08", "shipped_at(5i)"=>"59", "reached"=>"0", "reached_at(1i)"=>"2014", "reached_at(2i)"=>"8", "reached_at(3i)"=>"18", "reached_at(4i)"=>"08", "reached_at(5i)"=>"59"}}}, "commit"=>"Submit"}

Unpermitted parameters: _destroy
Unpermitted parameters: _destroy

Completed 500 Internal Server Error in 32ms

ActiveRecord::UnknownAttributeError (unknown attribute: box_id):
app/controllers/user_controller.rb:21:in `create'

最佳答案

HABTM

我认为问题出在您的 habtm 表上:

create_table "boxes_kinds", id: false, force: true do |t|
t.integer "ref_no", null: false
t.integer "kind_id", null: false
end

Rails has_and_belongs_to_many 表旨在包含每个关联表的 foreign_key:

enter image description here

您遇到的问题是,由于您的 表的box_idref_no,Rails 无法确定要将值保存到的列;因此调用您看到的异常。

我建议为您的 has_and_belongs_to_many 关联使用 association_foreign_keyforeign_key 参数:

#app/models/box.rb
Class Box < ActiveRecord::Base
has_and_belongs_to_many :kinds, foreign_key: "ref_no"
end

#app/models/kind.rb
Class Kind < ActiveRecord::Base
has_and_belongs_to_many :boxes, association_foreign_key: "ref_no"
end

关于ruby-on-rails - ActiveRecord::UnknownAttributeError in UserController#create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25360113/

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