Passing local variable to partial inside for each loop rails 3

非 Y 不嫁゛ 提交于 2019-12-10 15:36:08

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/12583823/passing-local-variable-to-partial-inside-for-each-loop-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!