当我从未显式调用它时,为什么我的实例变量会显示在视图中? [英] Why is my instance variable showing up on the view when I never called it explicitly?
问题描述
我正在 Rails 上编码,我已经从 rails g 模型
和 rails g 控制器
创建了一个应用程序 我已经成功创建了索引、显示、创建和新建在运行我的服务器并检查我完成的项目后,我遇到了这个问题,其中包含创建的优惠券数组的 @coupons
实例变量显示在视图索引页面中.我没有明确地调用它或它刚刚出现的任何东西.下面是我的 index.html.erb
和 CouponController
的代码.
views/index.html.erb
提供优惠券的商店列表</h1><div><%= @coupons.each do |coupon|%><h2><%=link_tocoupon.store,coupon_path(coupon)%></h2><%结束%>
<%= form_tag new_coupon_path, :method =>:做%><%= submit_tag "创建新优惠券" %><%结束%>
优惠券控制器
class CouponsController <应用控制器定义索引@coupons = Coupon.all结尾定义新结尾定义创建@coupon = Coupon.create(coupon_code: params[:coupon][:coupon_code], store: params[:coupon][:store])重定向到优惠券路径(@coupon)结尾高清秀@coupon = Coupon.find(params[:id])结尾结尾
请注意,我还删除了从 rails g controller
创建控制器时附带的 CSS
<%= @coupons.each do |coupon|%>
应该是
<% @coupons.each do |coupon|%>
<%=
导致 @coupons
在视图上输出.
I'm coding on rails and I have created an application from the rails g model
and rails g controller
I have successfully created the index, show, create and new actions and after running my server and checking my finished project I have this problem where my instance variable of @coupons
which contains an array of the created coupons, is showing up in the views index page. I didn't call it explicitly or anything it just showed up. Below is my code for my index.html.erb
and CouponController
.
views/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 %>
CouponController
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
Note that I also deleted the CSS that came when I created the controller from rails g controller
<%= @coupons.each do |coupon| %>
should be
<% @coupons.each do |coupon| %>
The <%=
causes @coupons
to be output on the view.
这篇关于当我从未显式调用它时,为什么我的实例变量会显示在视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!