2015-11-27 220 views
1

我的Rails應用程序中有三個模型。如下所述,用戶可以有更多的電話和電話可以屬於更多的客戶。Rails has_many:通過關聯表輸入

class Customer < ActiveRecord::Base 
    has_many :customer_phone_associations, dependent: :destroy 
    has_many :phones, through: :customer_phone_associations 
end 

class Phone < ActiveRecord::Base 
    has_many :customer_phone_associations 
    has_many :customers, through: :customer_phone_associations 
end 

class CustomerPhoneAssociation < ActiveRecord::Base 
    belongs_to :customer 
    belongs_to :phone 
end 

以客戶的形式,當用戶可以插入更多手機時,需要輸入文本,用逗號分隔。提交表格時,數據應插入三個數據庫表格中:客戶數據到客戶表格,電話到電話表格以及客戶和電話之間的關聯到額外表格。 我怎麼能創建這樣一個表單?

+0

試試cocoon gem https://github.com/nathanvda/cocoon – Saqib

回答

1

如果我理解的很好,您希望text_field的電話號碼用逗號分隔,有點像通常添加標籤的工作:122345, 6785433, 456567

這可能是一個有點棘手,但總體思路以實現包括使用虛擬屬性:

class Customer 
    has_many :phones, through: :bla 

    # this is the phone's list setter which will capture 
    # params[:customer][:add_phone_numbers] when you submit the form 
    def add_phone_numbers=(phones_string) 
    phones_string.split(",").each do |phone| 
     self.phones << phone unless phones.includes? phone 
    end 
    end 

    # this will display phones in the text_field 
    def add_phone_numbers 
    phones.join(", ") 
    end 
end 


= form_for @customer do |f| 
    = f.text_field :add_phone_numbers 

你仍然有工作做雖然,因爲對於一個你無法刪除電話號碼。

你可能想看看acts-as-taggable-on gem如何處理更多想法的問題。