Ricky Ahn
Ricky Ahn

Reputation: 191

Rails - combining two parameters together in the form

I dont know if this is possible but i want my outcome to look like this

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

so here is my form model

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

end

So i have a field called

:custom_field

and

:phone_number_28455

in the past i just did this

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

I just over righted the name value

and in my model instead of specifying each parameter in the post_tickets method i just passed it an argument of params

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

and it worked

I just need to figure out how to get my name value to look the way i want without overwritting it in the view

Upvotes: 0

Views: 360

Answers (1)

nzifnab
nzifnab

Reputation: 16092

fields_for to the rescue!

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

Documentation: http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

You can use fields_for with active-record objects to create nested attributes using has_nested_attributes_for. But in this case it doesn't look like you're necessarily using active_record. fields_for with just a symbol like this should give you field naming like you're looking for, and the params will come in like:

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

Upvotes: 3

Related Questions