0

I'm having trouble adding things from my New Form to display in the Index properly. I don't think they're being added to the database but I can't figure out why.

Routes

Rails.application.routes.draw do
  resources :coupons
end

new.html.erb

<%= form_tag coupons_path do %>
    <label>Coupon code:</label><br>
    <%= text_field_tag :'coupon[coupon_code]' %><br>
  
    <label>Store:</label><br>
    <%= text_field_tag :'coupon[store]' %><br>
  
    <%= submit_tag "Submit Coupon" %>

  <% end %>

Controller

class CouponsController < ApplicationController
    def index
        @coupons = Coupon.all
    end
    def show
        @coupon = Coupon.find(params[:id])
    end
    def new
    end

    def create
        @coupon = Coupon.new
        @coupon.coupon_code = params[:coupon_code]
        @coupon.store = params[:store]
        if @coupon.save
            redirect_to coupon_path(@coupon)
        else
            render :text => "Failed to create coupon"
        end
    end
end

My Index retains the new coupons but I think it only gets passed the id. It displays as /coupons/1 in an unordered list on the index page. Like-wise I can go to the show page but it only says "Coupon Code" and "Store," it doesn't include the data I passed it when I created it with the new form.

1 Answer 1

1

The coupon_code and store values are nested inside the coupon key since you're passing 'coupon[coupon_code]' and 'coupon[store]' as the field names to the text_field_tag method.

class CouponsController < ApplicationController
  def create
    @coupon = Coupon.new(coupon_params)
    # save coupon
  end

  private

  def coupon_params
    params.require(:coupon).permit(:coupon_code, :store)
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.