inimene
inimene

Reputation: 1650

Unable to pass variable to a partial

So I have this _index partial for comments that I want to display under pictures show page.

I am rendering the partial in my media view currently like this:

<div id="comments">
    <%= render partial: 'comments/index'  %>
</div>

My comments controller looks like this:

def index
        @comments = Comment.all
        render partial: 'comments/index', locals: { :comments => @comments }
end

And the coffescript code that I use to reload it looks like this:

setInterval (=> $('#comments').load('/comments')), 1000

Now in my view when I try to access the :comments variable that I sent to the partial, I am unable to do it. It contains no values.

How can I get the values properly to that partial?

Worth noting that the instance variable @comments is also not accessible from my partial.

Upvotes: 0

Views: 92

Answers (1)

davegson
davegson

Reputation: 8331

You're rendering the comments index partial from the picture show view.

The action in use here is picture show. When rendering the comments partial it will not call the comments controller. That's why the @comments variable isn't accessible.

So instead define the @comments in your picture controller

def show
  @picture = Picture.find(params[:id])
  @comments = @picture.comments
end

Then pass them from the picture/show view to your partial

<div id="comments">
  <%= render partial: 'comments/index', :locals => :comments => @comments  %>
</div>

Upvotes: 2

Related Questions