Help with your answer

What other question would you ask a new hire when you interview for Ruby on Rails position? Let's share together. Part II

=> asked by Jae Lee

Categories: ruby on rails   interview question  


<< back to questions

Building a Complex Form

Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary.

class Person < ActiveRecord::Base
  has_many :addresses
  accepts_nested_attributes_for :addresses
class Address < ActiveRecord::Base
  belongs_to :person

This creates an addresses_attributes= method on Person that allows you to create, update and (optionally) destroy addresses.

<%= form_for @person do |f| %>
    <%= f.fields_for :addresses do |addresses_form| %>
        <%= addresses_form.label :kind %>
        <%= addresses_form.text_field :kind %>
        <%= addresses_form.label :street %>
        <%= addresses_form.text_field :street %>
    <% end %>
<% end %>

Controller Namespace and Routing

You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an Admin:: namespace. You would place these controllers under the app/controllers/admin directory, and you can group them together in your router:

namespace :admin do

resources :posts, :comments


HTTP Verb Path Action Used for

GET /admin/posts index admin_posts_path

GET /admin/posts/new new new_admin_post_path

Shallow Nesting

resources :posts do

resources :comments, only: [:index, :new, :create]


resources :comments, only: [:show, :edit, :update, :destroy]

Adding Member Routes

You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.

resources :photos do

member do



This will recognize /photos/1/preview with GET, and route to the preview action of PhotosController, with the resource id value passed in params[:id]. It will also create the preview_photo_url and previewphotopath helpers.

Creating Paths and URLs from objects

resources :magazines do

resources :ads


<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>
<%= link_to 'Ad details', url_for([@magazine, @ad]) %>
<%=link_to 'Edit Ad', [:edit, @magazine, @ad] %>

over 3 years ago, by Jae Lee

Sponsored Links