Marc Pursals
Marc Pursals

Reputation: 792

Submitting an array in a form

I've been reading this question (Ruby on Rails: Submitting an array in a form) but it didn't answer my question.

I have this form:

<div class="signup pull-right">                        
  <div>                                                
   <p style="color: white">Create Doctor:</p>           
   <%= form_for(@doctor) do |d| %>                      
     <%= d.text_field :name[1], :placeholder => "name" %>                                                      
     <%= d.text_field :name[2], :placeholder => "surname" %>                                                   
     <%= d.text_field :email, :placeholder => "email" %>
     <%= d.text_field :password, :placeholder => "password" %>                                                 
     <%= d.text_field :password_confirmation, :placeholder => "password confirmation" %>                      

    <%= d.submit "Sumbit", class: "btn btn-small btn-primary pull-right", id: "boton" %>                      
  <% end %>                                            
 </div>        

where name is an array. What I want is to catch name and surname separately and join them inside name[]. I couldn't found the way to do it easily. Do you have any suggestion?

Thanks in advance.

Upvotes: 0

Views: 160

Answers (2)

sites
sites

Reputation: 21775

I would check till I have this html generated:

<input name='doctor[name][]'>

I would try:

<%= text_field_tag 'doctor[name][]' %>

Upvotes: 0

Billy Chan
Billy Chan

Reputation: 24815

You don't need such hack to solve the problem. Setting the attributes by virtual cattr_accessor would be simple and conventional.

class Doctor < ActiveRecord::Base
  cattr_accessor :first_name, :surname
  # others...
end

Then in form

<%= form_for(@doctor) do |d| %>                      
 <%= d.text_field :first_name, :placeholder => "first name" %>
 <%= d.text_field :surname, :placeholder => "surname" %>   

Then in controller

def create
  attr = params[:doctor]
  attr[:name] = "#{attr.delete!(:first_name)} #{attr.delete!(:surname)}"
  @doctor = Doctor.new(attr)
  if @doctor.save
    # blah blah
end

Upvotes: 1

Related Questions