我很好奇是否可以更新连接表中未在 ActiveRecord 中注册为模型的一堆记录。
我有 2 个类,比方说 A 和 B,由表 AsB 连接。
class A < ActiveRecord::Base
attr_accessible :A_name, :B_ids
has_and_belongs_to_many :Bs, join_table: :AsBs
end
class B < ActiveRecord::Base
attr_accessible :B_name, :A_ids
has_and_belongs_to_many :As, join_table: :AsBs
end
class CreateAsBs < ActiveRecord::Migration
def up
create_table :AsBs, id: :false do |t|
t.integer :A_id
t.integer :B_id
end
end
end
我还有一个带有 B 记录复选框的表单,它返回如下所示的参数哈希
params[:my_form]
>> { "B_name_1" => "1", "B_name_2" => "0", "B_name_3" => "0"}
#What means the user has chosen only first checkbox
我需要的是使用该参数哈希或其他基于其内容的自定义哈希来更新 A-B 关系。 最终我需要这个简单的例子来创建一个
A_id | B_id
1 | 1
在我的 :AsBs 表中记录并删除 1-2 和 1-3 记录(如果有)。
我显然可以创建一个 AsBs 模型并手动编辑它,但我希望使用 类似于 @a.Bs 或 @a.B_ids 的 update/update_all/update_attributes
有什么建议吗?
最佳答案
如果我理解正确的话你应该能够做到
@b.as = [@a]
@b.save
关于ruby-on-rails - 更新与 Rails 的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12075199/