【问题标题】:Rails Create Not Creating a New Record in the DatabaseRails Create 不在数据库中创建新记录
【发布时间】:2021-02-08 13:18:30
【问题描述】:

我无法从我的新表单中添加内容以正确显示在索引中。我不认为它们被添加到数据库中,但我不知道为什么。

路线

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 %>

控制器

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

我的索引保留了新的优惠券,但我认为它只会通过 id。它在索引页面的无序列表中显示为 /coupons/1。同样,我可以转到显示页面,但它只显示“优惠券代码”和“商店”,它不包括我在使用新表单创建它时传递的数据。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    coupon_codestore 值嵌套在 coupon 键中,因为您将 'coupon[coupon_code]''coupon[store]' 作为字段名称传递给 text_field_tag 方法。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多