1
votes

I have three models in my Rails applicaiton. As described below, user can have more phones and phone can belong to more customers.

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

In customer's form, I need text input when user can insert more phones, separated by commas. When the form is submitted, data should insert into three database tables: customer's data to Customer table, phone's to Phone table and association between customer and phone to extra table. How could I create such a form?

1

1 Answers

1
votes

If I understand well you want a text_field with phone numbers separated by commas a bit like usually adding tags work : 122345, 6785433, 456567.

This can be a little tricky, however the general idea to achieve that consists in using virtual attributes :

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

You'll still have work to do though, because for one you can't remove a phone number that way.

You may want to look at how acts-as-taggable-on gem deals with the problem for more ideas.