通过模态在我的索引页面内呈现显示页面

时间:2013-03-21 07:28:07

标签: ruby-on-rails modal-dialog partial-views

我正在使用模态弹出索引页面内的显示页面.....一切正常,直到我开始在显示页面部分使用@ 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

2 个答案:

答案 0 :(得分:3)

您正在使用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>

答案 1 :(得分: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>