2012-08-22 123 views
2

我很好奇,是否有可能更新未在ActiveRecord中註冊的連接表中的一堆記錄作爲模型。更新與Rails的多對多關係

我有2個類,讓我們說A和B,加入表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 

我也有複選框對於B記錄的形式,它返回params散列,像下面

params[:my_form] 
>> { "B_name_1" => "1", "B_name_2" => "0", "B_name_3" => "0"} 

#What means the user has chosen only first checkbox 

我需要的是更新AB的關係,使用PARAMS哈希或一個其他自定義哈希基於它的內容。 最後,我需要這個簡單的例子,我創建一個

A_id | B_id 
    1 | 1 

記錄:諮詢及法定組織表和刪除1-2和1-3的記錄,如果有的話。

我明明可以創建一個諮詢及法定組織模式和手動編輯它,但是我希望用 像更新/ update_all/update_attributes方法@爲a.Bs或@ a.B_ids

有什麼建議?

+1

它看起來就像你在騎了很多Rails的默認值。除非你有這樣一個非常有說服力的理由,否則最好遵守慣例。沒有很好的理由添加例外會使您的應用程序更難以維護。 – tadman

+1

回顧半年前我不知道如此簡單的方法是如何通過一個如此複雜的方式。 – shrimpsushi

回答

3

如果我理解正確的話,你應該能夠做到

@b.as = [@a] 
@b.save