10. Uploading Files
params[:picture]
<%= form_tag({:action => :upload}, :multipart =>
true) do %>
<%= file_field_tag 'picture' %>
<% end %>
<%= form_for @person, :multipart => true do |f| %>
<%= f.file_field :picture %>
<% end %>
params[:person][:picture]
Since Rails 3.1, it automatically sets the multipart/
form-data with file_field in the form_for
11. What gets
uploaded
def upload
uploaded_io = params[:person][:picture]
uploaded_io
File.open(Rails.root.join('public', 'uploads',
uploaded_io.original_filename), 'w') do |file|
file.write(uploaded_io.read)
end wb
end
an instance of a subclass of IO
• original_filename
• content_type : MIME type
15. Customizing Form
Builders Pro
using
helper <%= form_for @person do |f| %>
method <%= text_field_with_label f, :first_name %>
<% end %>
or
<%= form_for @person, :builder => LabellingFormBuilder do |
f| %>
using
<%= f.text_field :first_name %>
subclassing <% end %>
class LabellingFormBuilder <
ActionView::Helpers::FormBuilder
def text_field(attribute, options={})
label(attribute) + super
end
end
app/form_builders/labelling_form_builder.rb
16. Simple_form
• https://github.com/plataformatec/simple_form
• with Twitter Boostrap
• with Foundation 3
17. Params Naming
Client Server
Form
for model obj
params[:person]
“@person”
submit
24. Using :index
<%= fields_for 'person[address][primary]',
address, :index => address do |address_form| %>
<%= address_form.text_field :city %>
<% end %>
or
<%= fields_for 'person[address][primary][]', address
do |address_form| %>
<%= address_form.text_field :city %>
<% end %>
<input id="person_address_primary_1_city"
name="person[address][primary][1][city]" type="text"
value="bologna" />
25. Form to External
Resources - 1
form_tag
<%= form_tag 'http://farfar.away/
form', :authenticity_token => 'external_token') do %>
Form contents
<% end %>
<%= form_tag 'http://farfar.away/
false
form', :authenticity_token => false) do %>
Form contents
<% end %> payment gateway
26. Form to External
Resources - 2
form_for
<%= form_for @invoice, :url =>
external_url, :authenticity_token => 'external_token'
do |f|
Form contents
<% end %>
<%= form_for @invoice, :url =>
external_url, :authenticity_token => false do |f|
Form contents
<% end %>
27. Complex forms
ROR Lab. screencasts
Railscasts by Ryan Bates
• Complex Forms Part 1 - Episode #73
• Complex Forms Part II - Episode #74
• Complex Forms Part III - Episode #75
• Nested Model Form (revised) - Episode #196