0

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.

Community
  • 1
  • 1
Marc Pursals
  • 762
  • 1
  • 8
  • 23

2 Answers2

1

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
Billy Chan
  • 24,625
  • 4
  • 52
  • 68
  • why cattr_accesor and not attr_accessor? could you explain? – sites Aug 07 '13 at 16:17
  • @juanpastas, in this case they should be the same as we only need the attributes to work on instance level. Both can do that. I just get used to `cattr_accessor` which is a Rails method but not a Ruby one. – Billy Chan Aug 07 '13 at 16:29
0

I would check till I have this html generated:

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

I would try:

<%= text_field_tag 'doctor[name][]' %>
sites
  • 21,417
  • 17
  • 87
  • 146