gpt4 book ai didi

ruby-on-rails - Mechanize HABTM 连接表的质量分配错误

转载 作者:行者123 更新时间:2023-12-04 16:20:50 26 4
gpt4 key购买 nike

问题是我收到此错误:

ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: amenity_id

当我运行此代码时:
task import_amenities: :environment do

agent = Mechanize.new

Kindergarten.find_all_by_public(false).each do |k|
p = agent.get(k.uri)
amenities = p.search("td td tr:nth-child(11) td:nth-child(2)").text.split(/(;|,) */)
amenities.each do |a|
am = Amenity.find_or_create_by_name!("#{a}")
k.update_attributes(amenity_id: am.id)
end
end
end

幼儿园和便利设施通过 HABTM 关系联系起来,定义如下:

幼儿园.rb
class Kindergarten < ActiveRecord::Base
attr_accessible :location, :name, :public, :uri, :address, :contact,
:phone, :url, :email, :description,
:password, :password_confirmation, :amenity_ids
has_and_belongs_to_many :amenities
end

便利设施.rb
class Amenity < ActiveRecord::Base
attr_accessible :name, :kindergarten_ids
has_and_belongs_to_many :kindergartens
end

这是连接表的迁移:
class CreateKindergartensAmenitiesJoinTable < ActiveRecord::Migration
def up

create_table :kindergartens_amenities, :id => false do |t|
t.integer :kindergarten_id
t.integer :amenity_id
end
end
end

该错误是由 rake 任务中的这一行引起的:
k.update_attributes(amenity_id: am.id)

在我完成批量分配之前,控制台中的一切似乎都运行良好。而且我想我真的在这里搞砸了,因为我以前从未使用过 HABTM。

有什么想法吗?

最佳答案

由于这个错误,我昨晚无法休眠,但我终于找到了解决方案。

代码中有一些问题,当我开始手动在数据库中挖掘和添加数据时,我注意到的第一个问题是连接表的名称有误。修复:

class RenameKindergartensAmenitiesTable < ActiveRecord::Migration
def up
rename_table :kindergartens_amenities, :amenities_kindergartens
end
end

显然,habtm 协会必须将内容按字母顺序排列在标题中。 source

第二个问题是我假设
k.amenity_id = am.id

将为现有的每个便利设施添加一个 amenity_id/kindergarten_id。实际上 k.amenity_id 没有任何意义(尤其是在许多 id 的情况下)。有效的解决方案是这样的:
amenities.each do |a|
am = Amenity.find_or_create_by_name!("#{a}")
k.update_attributes(amenity_ids: k.amenity_ids.push(am.id))
end

我没有修改 attr_accessible任何地方

关于ruby-on-rails - Mechanize HABTM 连接表的质量分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12449573/

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