将局部变量传递给每个循环轨道的部分内部 3 [英] Passing local variable to partial inside for each loop rails 3

查看:43
本文介绍了将局部变量传递给每个循环轨道的部分内部 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我渲染部分的代码(@parties 集合正在正确生成,我已经测试过):

 <% @parties.each do |party|%><div class="item"><%= 渲染 'party/party', :object =>派对%>

<%结束%>

这是部分中的代码:

<%= party.name %>

但是,我收到以下错误:

 未定义的方法 `name' for nil:NilClass

我不知所措,请有人帮忙:-|

此外,这是控制器渲染包含局部视图的代码(控制器称为 default_controller):

def 索引@party = Party.all结尾

这不是party_controller 有什么后果吗?

解决方案

我已经尝试过类似下面的方法并且有效

<%= render :partial =>'派对', :object =>派对%>

我可以像party.name那样访问.局部变量以部分名称命名,这里是party.

注意:我假设你的两个部分都是parties_controller.所以这应该有效.

更新:这是我再次尝试的

class PostsController <应用控制器#…………定义索引@posts = Post.all@comments = Comment.all #<---- 从 PostsController 加载评论#…………结尾结尾

<小时>

#views/posts/index.html.erb<% @comments.each 做 |comment|%><%=render :partial=>"comments/comment", :object=>comment %><%结束%>

<小时>

#views/comments/_comment.html.erb<%= comment.body %>

<小时>

它的工作:)

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?

解决方案

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

这篇关于将局部变量传递给每个循环轨道的部分内部 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆