I’ve just started to use Partials in my rails application, at the moment i have the following code in my application.html.erb
<%= render 'categories/categorieslist' %>
This links to _categorieslist.html.erb in my views/categories/ folder
At the moment this partial contains hard coded hyperlinks
<ul class="unstyled">
<li style="padding-bottom:5px"><a href="#">Item A»</a></li>
<li style="padding-bottom:5px"><a href="#">Item B»</a></li>
</ul>
My aim is to have these categories coming from the database, e.g
<ul class="unstyled">
<% @categories.each do |category| %>
<li style="padding-bottom:5px"><a href="#"><%= category.name %> » </a></li>
<% end %>
</ul>
I have tried adding a categorieslist method in the categories controller e.g
def categorieslist
@categories = Category.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @categories }
end
end
but this is not being called by the partial (and i don’t feel this is even the correct way to do it), and is showing the error
NoMethodError in Store#index
on the line <% @categories.each do |category| %>
My question is how do i pass into the partial in the application.html.erb file, the categories object that usually would come from a controller method in the categories controller?
Any help would be great.
You can send
localeswith your partial call in your view and pass variables to that partial.For example (this is a partial shortcut):
Your view from which you call the partial
Your partial categories/_categorieslist.html.erb (note there is no @ with the variable)
For further information (and the long version), see 3.4.4 Passing Local Variables in the Rails Guides.