Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing local variable to partial inside for each loop rails 3

This is my code for rendering the partial (the @parties collection is being generated correctly, I have tested that):

        <% @parties.each do |party| %>
            <div class="item">
              <%= render 'parties/party', :object => party  %>
            </div>
        <% end %>

And this is the code in the partial:

<%= party.name %>

However, I get the following error:

undefined method `name' for nil:NilClass

I'm at my wits end, someone please help :-|

Also, this is the code for the controller to render the view containing the partial (The controller's called default_controller):

def index
    @parties = Party.all
end

Is it of any consequence that this isn't the parties_controller?

like image 496
nicohvi Avatar asked Sep 25 '12 13:09

nicohvi


1 Answers

I've tried something like below and it worked

<%= render :partial => 'party', :object => party  %>

and I can access like party.name. the local variable is named after the partial name which is party here.

Note: Im assuming that your both partials are of parties_controller. So this should work.

Update: Here is what ive tried with again

class PostsController < ApplicationController
    #... ...
    def index
        @posts = Post.all
        @comments = Comment.all #<---- Loading comments from PostsController
        #... ...
    end  
end

#views/posts/index.html.erb

<% @comments.each do |comment| %>
    <%= render :partial=>"comments/comment", :object=>comment %>
<% end %>

#views/comments/_comment.html.erb

<%= comment.body %>

And its working :)

like image 97
Samiron Avatar answered Oct 10 '22 02:10

Samiron