Reputation: 515
I'm curious if it's possible to update a bunch of records in a join table that's not registered in an ActiveRecord as a model.
I have 2 classes, lets say A and B, joined by table AsBs.
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
I also have a form with checkboxes for B records, which returns a params hash like the one below
params[:my_form]
>> { "B_name_1" => "1", "B_name_2" => "0", "B_name_3" => "0"}
#What means the user has chosen only first checkbox
What I need is to update the A-B relations, using that params hash or other custom hash based on it's content. Eventually I need this simple example to create a
A_id | B_id
1 | 1
record in my :AsBs table and remove 1-2 and 1-3 records, if any.
I obviously can create an AsBs model and edit it manually, but I'd expect using something like update / update_all / update_attributes for @a.Bs or @a.B_ids
Any advice?
Upvotes: 2
Views: 2092
Reputation: 1317
If I understand correctly you should be able to do
@b.as = [@a]
@b.save
Upvotes: 4