Ruby on rails Rails有很多:通过表单输入的关联

Ruby on rails Rails有很多:通过表单输入的关联,ruby-on-rails,ruby,Ruby On Rails,Ruby,我的Rails应用程序中有三种型号。如下所述,用户可以拥有更多的手机,手机可以属于更多的客户 class Customer < ActiveRecord::Base has_many :customer_phone_associations, dependent: :destroy has_many :phones, through: :customer_phone_associations end class Phone < ActiveRecord::Base ha

我的Rails应用程序中有三种型号。如下所述,用户可以拥有更多的手机,手机可以属于更多的客户

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
class客户
在客户表单中,当用户可以插入更多电话时,我需要文本输入,并用逗号分隔。提交表单时,数据应插入三个数据库表:客户数据到客户表、电话到电话表以及客户和电话到额外表之间的关联。
我怎样才能创建这样一个表单呢?

如果我理解得很清楚,你想要一个带有电话号码的
文本字段
,用逗号分隔,这有点像通常添加标签的工作:
12234567854334567

这可能有点棘手,但实现这一点的总体思路在于使用虚拟属性:

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
class客户
有很多:电话,通过::bla
#这是手机的列表设置器,它将捕获
#提交表单时,参数[:客户][:添加电话号码]
def添加电话号码=(电话字符串)
电话|字符串。拆分(“,”)。每个都有|电话|
self.phones尝试蚕茧宝石