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 I

=> asked by Jae Lee

Categories: ruby on rails   interview question  


<< back to questions

Rendering Partial

<%=render "shared/menu"%>

<%= render partial: "product" %>

<%=render partial: "product", locals: {product: @product} %>

use item as a local object name in a partial view file

<%=render partial: "product", as: "item"%>

<%= render partial: "product", locals: {product: @item} %>

<%=render partial: "product", object: @item%>

use item as a local object name, pass item object to the partial view file

<%= render partial: "product", object: @item, as: "item" %>

Rendering Collections

<% @products.each do |product| %>

<%= render partial: "product", locals: { product: product } %>

<% end %>

the block of codes above can be rewritten in a single line

<%=render partial: "product", collection: @products%>

even shorter

<%=render @products%>

spacer template

<%=render @products, spacertemplate: "productruler"%>


in a layout file

<%= yield :special_script %>

another special layout page?

<% content_for :special_script do %>

<% end %>

Render & Redirect

The way to handle returning responses to an HTTP request is with redirectto. As you've seen, render tells Rails which view (or other asset) to use in constructing a response. The redirectto method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call.

Form Helper


def new

@article =


the corresponding view, do create action on submit

<%= form_for @article, url: {action: "create"}, html: {class: "nifty_form"} do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :body, size: "60x12" %>
  <%= f.submit "Create" %>
<% end %>

The name passed to formfor controls the key used in params to access the form's values. Here the name is article and so all the inputs have names of the form article[attributename]. Accordingly, in the create action params[:article] will be a hash with keys :title and :body. You can read more about the significance of input names in the parameter_names section.

another example

<%= form_for@post do |f| %> ... <% end %>

in case it is an edit form

<%= form_for@post, as::post, url:post_path(@post), method::patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %>

in case it is a new form

<%= form_for@post, as::post, url:posts_path, html: { class: "new_post", id: "new_post" } do |f| %>

almost 3 years ago, by Jae Lee

Sponsored Links