Ruby on rails ActiveRecord::UserController中的UnknownAttributeError#创建
我从学习rails开始,为此,我首先开发了一个具有嵌套属性的shipping应用程序。基本上,我有型号Ruby on rails ActiveRecord::UserController中的UnknownAttributeError#创建,ruby-on-rails,activerecord,ruby-on-rails-4,Ruby On Rails,Activerecord,Ruby On Rails 4,我从学习rails开始,为此,我首先开发了一个具有嵌套属性的shipping应用程序。基本上,我有型号User,Box和BoxKind表,其中HABTM位于Box和Kind之间 用户模型 class User < ActiveRecord::Base has_many :boxes accepts_nested_attributes_for :boxes end class Box < ActiveRecord::Base belongs_to :user, :foreig
User
,Box
和BoxKind
表,其中HABTM位于Box
和Kind
之间
用户模型
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
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具有且属于多个
表包含每个相关表的外键
:
您遇到的问题是,由于您的表具有box\u id
作为ref\u no
,Rails无法确定要将值保存到的列;因此调用您看到的异常
我建议使用关联\u外键
或外键
参数作为的has\u和\u属于\u多个
关联:
#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
#app/models/box.rb
类框
您必须更改表格中的方框。删除ref_no并添加box_id。因为join table保存相关表的id列,如{model_name}\u id
。您还需要从用户许可参数中删除id列,或者说是父许可参数。id列仅适用于子模型。另外,如果您想在编辑父对象时销毁任何关联的子对象,也可以添加_destory以允许使用参数
def user_box_params
params.require(:user).permit(:name, :email, :address, :postcode, :tel_no, :state,
boxes_attributes: [:id, :ref_no, :quantity, :collected_at, :destination_country, :destination_country_address, :shipped, :shipped_at, :reached, :reached_at, _destroy,
kinds_attributes: [:id, :big, :small, :odd, :trunck, _destroy]])
end
你能在这里粘贴你的控制台日志吗?当然。我已经更新了我的问题。谢谢
def user_box_params
params.require(:user).permit(:name, :email, :address, :postcode, :tel_no, :state,
boxes_attributes: [:id, :ref_no, :quantity, :collected_at, :destination_country, :destination_country_address, :shipped, :shipped_at, :reached, :reached_at, _destroy,
kinds_attributes: [:id, :big, :small, :odd, :trunck, _destroy]])
end