2013-03-21 55 views
2

我正在使用模式来弹出索引页面内的显示页面.....一切正常,直到我开始在我的节目中使用@ product.name页面部分。渲染显示页面,在我的索引页面通过模式

我得到这个错误:

undefined method `name' for nil:NilClass 

我知道这是一个简单的办法,请大家帮忙....新轨道 这是我的代码:

查看

_show .html.erb

<div id="myModal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
    <div class="content-inner hero-unit"> 
    <h1 class="pump-up center"> 
     <br> 
     <strong>Coming Soon.</strong></h1> 
     <br><br> 
     <p> 
     <b>Name: </b> 
     **<%= @product.name %>** 
     </p> 
    </div> 
</div> 

index .html.erb

<%= render :partial => "show", :locals => { :product => @product } %> 

<div class="row"> 
    <% @products.each do |product| %> 
     <div class="span3"> 

     <a href="#myModal" role="button" data-toggle="modal"> 
     <%=(image_tag product.photo(:medium))%></a> 

     </div> 
    <% end %> 
</div> 

模型

product.rb

class Product < ActiveRecord::Base 
    attr_accessible :name, :photo 
end 

控制器

products_controller.rb

class ProductsController < ApplicationController 

    def show 
    @product = Product.find(params[:id]) 
    end 


    def index 
    @products = Product.all 
    end 

end 
+0

你好浪涌你是怎么解决“不同产品上的同名产品问题”的? – learner 2015-05-03 04:11:01

回答

2

您正在使用index操作呈现index模板,因此您的作用域中的@productNil。您必须在每个产品的循环内调用渲染部分。

index.html.erb应该是类似的东西:

<div class="row"> 
    <% @products.each do |product| %> 
     <div class="span3"> 
     <%= render :partial => "show", :locals => { :product => product } %> 
     <a href="#myModal" role="button" data-toggle="modal"> 
     <%=(image_tag product.photo(:medium))%></a> 

     </div> 
    <% end %> 
</div> 
+0

我仍然收到相同的错误...:/ @Pigueiras – 2013-03-21 07:55:52

+0

您也正在错误地使用部分中的变量。当你传递一个局部变量并引用它时,你应该用'product'调用你的case。 – Pigueiras 2013-03-21 08:00:12

+0

当然....大声笑x)非常感谢你.. @Pigueiras – 2013-03-21 08:02:10

2

对于任何人懒漫游周围像我这样的解决方案:

index.html.erb应该是类似的东西:

<div class="row"> 
<% @products.each_with_index do |product, index| %> 
    <div class="span3"> 
    <%= render :partial => "show", :locals => { :product => product, :index => index } %> 
    <a href=<%="#myModal_#{index}"%> role="button" data-toggle="modal"> 
    <%=(image_tag product.photo(:medium))%></a> 
    </div> 
<% end %> 
</div> 

show.html.erb应该是这样的:

<div id=<%="myModal_#{index}"%> class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
<div class="content-inner hero-unit"> 
<h1 class="pump-up center"> 
    <br> 
    <strong>Coming Soon.</strong></h1> 
    <br><br> 
    <p> 
    <b>Name: </b> 
    **<%= product.name %>** 
    </p> 
</div> 
</div>