0

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

 <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

它奏效了

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

4

1 回答 1

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只需像这样的符号就可以为您提供所需的字段命名,并且参数将如下所示:

contacts: {
  custom_field: {
    phone_number_28445: "your value here"
  }
}
于 2013-09-12T23:03:13.190 回答