Rails - 在表单中将两个参数组合在一起

时间:2013-09-12 22:59:20

标签: ruby-on-rails ruby ruby-on-rails-3 forms

我不知道这是否可行,但我希望我的结果看起来像这样

 <input id="contacts_custom_field_phone_number_28445" name="contacts[custom_field][phone_number_28445]" size="30" type="text">

所以这是我的表单模型

class Form
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Translation
  extend  ActiveModel::Naming

  attr_accessor :config, :client, :subject, :email, :phone_number_28445, 
            :custom_field_company_28445, :description, :custom_field

  validates_presence_of :subject, :message => '^Please enter your name'
  validates_presence_of :description, :message => '^Question(s), and/or feedback can not be blank'
  validates :email, presence: true  
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end

    self.config = YAML.load_file("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
self.client = Freshdesk.new(config[:url], config[:api_key], config[:password])
  end

  def post_tickets
    client.post_tickets({
     :subject => "Web Inquiry From, #{subject}", 
     :email => email,
     :custom_field => custom_field,
     :phone_number_28445 => phone_number_28445,
     :description => description
    })
 end

 def persisted?
   false
 end

所以我有一个名为

的字段
:custom_field

:phone_number_28455

过去我刚刚做了这个

= f.text_field :custom_field_phone_number_28445, name: 'contacts[custom_field][phone_number_28445]'

我刚刚过了名字值

在我的模型中,而不是在post_tickets方法中指定每个参数,我只是传递了一个参数params

  def post_tickets(params)
    client.post_tickets(params)
  end

并且有效

我只需要弄清楚如何让我的名字值看起来像我想要的方式而不会在视图中覆盖它

1 个答案:

答案 0 :(得分:3)

fields_for救援!

= f.fields_for :custom_field do |cust|
  = cust.text_field :phone_number_28445

文档:http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

您可以将fields_for与活动记录对象一起使用has_nested_attributes_for创建嵌套属性。但在这种情况下,看起来你不一定使用active_record。只有这样的符号的fields_for应该像你正在寻找的那样给你字段命名,并且params会像:

contacts: {
  custom_field: {
    phone_number_28445: "your value here"
  }
}