表格中的第一个元素不能为空

时间:2016-08-17 09:41:55

标签: ruby-on-rails

我遇到了这个问题

.container.weekdays
  .row
   .col-sm-3  
      .panel-default data-day="#{@weekdays[0]}"
       .h3 
         |Today's menu.            
         =@weekdays[0]
        br
         =link_to "Today's menu", admin_menu_path("#{@weekdays[0]}"),   class: 'today', remote: true
      hr
      hr
    fieldset
      legend Update menu here
      =form_for [:admin, @menu] ,method: :patch, remote: true do |f|
        p
          = f.select(:type, options_for_select(["", :First, :Second, :Drink], include_blank: true))
        p
          =f.label 'Name'
          =f.text_field :name
        p
          =f.label 'Price'
          =f.number_field :price              
        = f.submit

和菜单控制器,其中show action正常工作

class Admin::MenusController < Admin::BaseController
  before_action :set_menu , only:[:update]
  def show  
    @menu = Menu.where(day: params[:id])  
  end

  def update 
    @menu = Menu.where(day: DateTime.now.strftime("%A"))       
    @item = menu_params.type.constantize.new(name: menu_parms.name, price: params[:menu][:price], menu: @menu)
    @item.save
  end

  private  
  def menu_params
    params.require(:menu).permit(:type, :name, :price)
  end
end

我收到的第一个论点是在表单更新中是nill,需要一些帮助。我确实认为代码很糟糕,但我仍然是新手,它应该首先工作,而不是我试图重构

为了更好地理解这里的问题,菜单模型

class Menu < ApplicationRecord
  has_many :dishes

  delegate :firstmeals, :secondmeals, :drinks, to: :dishes

  validates :day, presence: true
  validates :day, uniqueness: true

  def self.get_menu day
    Menu.where(day: day).first
  end 

  private
  def to_param
    day
  end  

所以我实际上并不需要更新菜单,我只需要创建一个菜。但同样的问题仍然存在

  fieldset
      legend Update menu here
      =form_for [:admin, @dish], method: :patch, remote: true do |f|
        p
          = f.select(:type, options_for_select(["", :First, :Second, :Drink], include_blank: true))
        p
          =f.label 'Name'
          =f.text_field :name
        p
          =f.label 'Price'
          =f.number_field :price              
        = f.submit

1 个答案:

答案 0 :(得分:2)

include_blank应在options_for_select

之外
= f.select(:type, options_for_select([:First, :Second, :Drink]), { include_blank: true })

如果您要传递include_blank选项,则无需手动添加空字符串

select

的文档