0

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 Image of said issue

Kenkuts
  • 59
  • 1
  • 11

2 Answers2

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

should be

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

The <%= causes @coupons to be output on the view.

jvillian
  • 19,953
  • 5
  • 31
  • 44
2

The problem is that you are using <%= %> and not <% %>.

<%= %> outputs the value of an expression. The return value of #each is an array.

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

This can be somewhat confusing but remember that you are using #each for the side effects - and not the return value. For each iteration <h2><%= link_to coupon.store, coupon_path(coupon) %></h2> is added to the string buffer (the rendered view).

max
  • 96,212
  • 14
  • 104
  • 165