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
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 end class Address < ActiveRecord::Base belongs_to :person end
This creates an addresses_attributes= method on Person that allows you to create, update and (optionally) destroy addresses.
<%= form_for @person do |f| %> Addresses: <ul> <%= f.fields_for :addresses do |addresses_form| %> <li> <%= addresses_form.label :kind %> <%= addresses_form.text_field :kind %> <%= addresses_form.label :street %> <%= addresses_form.text_field :street %> </li> <% end %> </ul> <% end %>
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
resources :posts do
resources :comments, only: [:index, :new, :create]
resources :comments, only: [:show, :edit, :update, :destroy]
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
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.
resources :magazines do
<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %> <%= link_to 'Ad details', url_for([@magazine, @ad]) %> <%=link_to 'Edit Ad', [:edit, @magazine, @ad] %>