0

what does this line of code do it is from the form_for method in rails ?

object = record.is_a?(Array) ? record.last : record

2 Answers2

2

First off, here is the actual line of code, and the full context:

def form_for(record, options = {}, &block)
  raise ArgumentError, "Missing block" unless block_given?
  html_options = options[:html] ||= {}

  case record
  when String, Symbol
    object_name = record
    object = nil
  else
    object = record.is_a?(Array) ? record.last : record
    raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
    object_name = options[:as] || model_name_from_record_or_class(object).param_key
    apply_form_for_options!(record, object, options)
  end
  [...]
end

It says: if record is an array, then assign the last element of the array to object, otherwise assign record itself to object.

So basically, it describes how to handle the case when you don't know whether you'll be getting an array of records or just one record.

There are a couple of cases where you pass an array into form_for.

Namespaced routes:

<%= form_for([:admin, @post]) do |f| %>
  ...
<% end %>

Nested resources:

<%= form_for([@document, @comment]) do |f| %>
 ...
<% end %>

Note that in each case, it's the last element in the array that the form is actually for; the earlier elements provide context (on either namespaces or nesting). More in the docs.

Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
0

It checks if the variable record is an array, and if it is, gets the last element in the array, and if it isn't gets the record itself.

This is useful for nested routing, for instance if you had a model Book that belongs to User, and in your routes you nest them:

# config/routes.rb

resources :users do
  resources :books
end

Then for the resource you'd need to specify form_for [@user, @book] do |f|


More on form_for with nested resources: form_for with nested resources

Also it uses the is_a? method: http://ruby-doc.org/core-1.9.3/Object.html#method-i-is_a-3F

And the ternary operator: Ruby ternary operator without else

Community
  • 1
  • 1
AJcodez
  • 31,780
  • 20
  • 84
  • 118