【问题标题】:Rails has_many :through associations form inputRails has_many:通过关联表单输入
【发布时间】:2016-03-01 12:29:01
【问题描述】:

我的 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

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

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案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 如何处理该问题以获得更多想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多