select 表单中的值未提交

select values in a form not getting submitted

我不太确定我遗漏了什么,当我使用开发工具时,表单在 html 中正确显示,但唯一没有提交的值是下拉列表中的那个下。

我查看了我的数据库,它根本没有提交任何值我做错了什么,我在下面发布了我的代码。

******************表格*********************

= form_for @menu_price do |f|
  - if @menu_price.errors.any?
    #error_explanation
      h2 = "#{pluralize(@menu_price.errors.count, "error")} prohibited this menu_price from being saved:"
      ul
        - @menu_price.errors.full_messages.each do |message|
          li = message

  .form-group
    = f.label Category
    = f.select :category_id,  options_for_select( @categories_options),{prompt: "Select a category"}
  .form-group
    = f.label :price
    = f.number_field :price
  .form-group
    = f.label :description
    = f.text_field :description
  .form-group
    = f.label :serves
    = f.text_field :serves

  = f.submit
  = link_to 'Back', menu_prices_path, class:'button'

******************控制器******************

class MenuPricesController < ApplicationController
  before_action :set_menu_price, only: [:show, :edit, :update, :destroy]

  def index
    @menu_prices = MenuPrice.all
  end


  def show
    @categories = Category.all
  end

  def new
    @menu_price = MenuPrice.new
    @categories_options = Category.all.map{|u| [ u.name, u.id ] }
  end

  def edit
    @categories_options = Category.all.map{|u| [ u.name, u.id ] }
  end


  def create
    @menu_price = MenuPrice.new(menu_price_params)

    respond_to do |format|
      if @menu_price.save
        format.html { redirect_to @menu_price, notice: 'Menu price was successfully created.' }
        format.json { render :show, status: :created, location: @menu_price }
      else
        format.html { render :new }
        format.json { render json: @menu_price.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @menu_price.update(menu_price_params)
        format.html { redirect_to @menu_price, notice: 'Menu price was successfully updated.' }
        format.json { render :show, status: :ok, location: @menu_price }
      else
        format.html { render :edit }
        format.json { render json: @menu_price.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @menu_price.destroy
    respond_to do |format|
      format.html { redirect_to menu_prices_url, notice: 'Menu price was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_menu_price
      @menu_price = MenuPrice.find(params[:id])
    end

    def menu_price_params
      params.require(:menu_price).permit(:category, :price, :description, :serves)
    end
end

在你看来你有

  = f.select :category_id

在您的 MenuPricesController 中您有

params.require(:menu_price).permit(:category, ..)

只需将 :category 更改为 :category_id

您需要将 category_id 而不是 category 列入白名单。将您的 menu_price_params 更改为

def menu_price_params
   params.require(:menu_price).permit(:category_id, :price, :description, :serves)
end