问题是我收到此错误:
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 之前从未使用过。
有什么想法吗?