2

我正在使用模态在索引页面内弹出显示页面.....一切正常,直到我开始在我的显示页面部分中使用@product.name。

我收到此错误:

undefined method `name' for nil:NilClass

我知道这是一个简单的解决方法,请帮助....rails 新手 这是我的代码:

意见

_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>

模型

产品.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
4

2 回答 2

3

您正在index使用操作渲染模板,index因此@product在您的范围内是Nil. 您必须在每个产品的循环内调用部分渲染。

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>
于 2013-03-21T07:47:46.030 回答
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>
于 2013-06-26T15:53:16.280 回答