Reno
Reno

Reputation: 2982

Rending a partial from a method - local variable not passing?

Rails 2.3.5

This is the first time I've tried to render a partial from a method on an AJAX call where the partial needs a local variable. The query is working fine, I can't figure out what's wrong and I can't find anything through searches so far. The partial is being rendered with the local passed to it the exact same way in the view.

@group = Group.find(params[:group_id])

respond_to do |format|
  format.html {render :partial => 'group_show_user_list', :locals=>{:users=>@group.users}}
  format.js
end

error:

ActionView::TemplateError (undefined local variable or method `users' for #<ActionView::Base:0x8a33030>) on line #16 of app/views/groups/_group_show_user_list.html.erb:
13:     <tbody>
14: 
15: 
16: <% users.each do |user| %>
17: 
18:          <tr id="dir_user_<%= user.id %>">
19:             <td>

Is it possible to pass a local variable to a partial when the partial is rendered from inside a method? Or should I be changing the partial over to instance variable?

Thanks - much appreciated!

EDIT:

This isn't really an answer but in the controller I added:

@users = @group.users

and in the Partial I added:

<% users = users || @users %>

I couldn't really change the whole partial over because the partial is initially called from a Group index page and needs a unique group of users based on the one Group selected when the 'show' page is first generated.

I'd still love to know why passing a local to a partial in a method isn't working - like if I need to do it a different way than when you pass locals to a partial in a view, or if passing locals just doesn't work from a method - Thanks!

Upvotes: 1

Views: 1454

Answers (2)

janbak
janbak

Reputation: 1

Maybe I found a (not the) solution to your question. Instead of setting a local var in your partial <% users = users || @users %> (according to what I understand, you should only use local vars in partials), you can set the locals in the render command in the ..js.erb file, like:

.update("<%= escape_javascript(render(:partial => "/users/group_list", :locals => { :users => @users } )) %>

you still have to create a @users var in the controller method.

Upvotes: 0

stef
stef

Reputation: 14268

Are you sure that it is respond_to :html? In other Rack-based apps I often find that it's respond_to :js for AJAX calls.

For testing you can use render :blah, :layout=>request.xhr? to turn layout on or off for ajax requests so you can test the route in a browser.

You might also want to do:

@group = Group.find(params[:group_id])
render :nothing => true, :status => :not_found and return unless @group

Which would at least give you an AJAX error in the browser.

Upvotes: 1

Related Questions