首页 > 解决方案 > 当我从未明确调用它时,为什么我的实例变量会显示在视图上?

问题描述

我在 Rails 上编码,我已经创建了一个应用程序rails g modelrails g controller我已经成功创建了索引、显示、创建和新操作,在运行我的服务器并检查我完成的项目之后,我遇到了这个问题,其中我的实例变量@coupons包含一个创建的优惠券数组,显示在视图索引页面中。我没有明确地称呼它或它刚刚出现的任何东西。下面是我的代码 myindex.html.erbCouponController.

意见/index.html.erb

<h1> List of Stores with Coupons</h1>

<div>
<%= @coupons.each do |coupon| %>
  <h2><%= link_to coupon.store, coupon_path(coupon) %></h2>
<% end %>
</div>

<%= form_tag new_coupon_path, :method => :get do %>
  <%= submit_tag "Create New Coupon" %>
<% end %>

优惠券控制器

class CouponsController < ApplicationController
  def index
    @coupons = Coupon.all
  end

  def new
  end

  def create
    @coupon = Coupon.create(coupon_code: params[:coupon][:coupon_code], store: params[:coupon][:store])

    redirect_to coupon_path(@coupon)
  end

  def show
    @coupon = Coupon.find(params[:id])
  end
end

请注意,我还删除了创建控制器时的 CSSrails g controller 上述问题的图片

标签: ruby-on-railsrubyview

解决方案


<%= @coupons.each do |coupon| %>

应该

<% @coupons.each do |coupon| %>

要在视图上输出的<%=原因。@coupons


推荐阅读