Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does local_assigns work in Rails?

I've been googling around about this and can't find the right path. I'm working on a Rails app that is using a method called local_assigns. This appears to be something in Rails or a gem, and not specific to my app, but it's used for rendering a partial in different contexts, such as this:

<% if local_assigns[:custom_name] %>
  <li><%= custom_name %></li>
<% else %>

or also this:

<%= render "discussions/complementary/#{local_assigns[:action] || params[:action]}" %>

Is this is Rails method? Where can I find more documentation about this?

like image 295
Lee McAlilly Avatar asked May 30 '12 15:05

Lee McAlilly


People also ask

What is render partial Rails?

Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

How do I render in Ruby on Rails?

From the controller's point of view, there are three ways to create an HTTP response: Call render to create a full response to send back to the browser. Call redirect_to to send an HTTP redirect status code to the browser. Call head to create a response consisting solely of HTTP headers to send back to the browser.

What are partials Ruby?

Ruby on Rails Views Partials Partial templates (partials) are a way of breaking the rendering process into more manageable chunks. Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates.


1 Answers

local_assigns is a Rails view helper method that you can check whether this partial has been provided with local variables or not.

Here you render a partial with some values, the headline and person will become accessible with predefined value.

<%= render "shared/header", { :headline => "Welcome", :person => person } %> 

In shared/header view:

Headline: <%= headline %> First name: <%= person.first_name %> 

Here is how you check these variables has passed in or not:

<% if local_assigns.has_key? :headline %>   Headline: <%= headline %> <% end %> 

Check this document for more detail on the section Passing local variables to sub templates.

like image 137
Chamnap Avatar answered Oct 07 '22 11:10

Chamnap