簡體   English   中英

simple_form無法驗證輸入

[英]Simple_form not validating input

我有一個Rails應用程序,用戶在其中提交一個表單來創建一個項目,然后將其重定向到他們剛剛創建的項目。

我遇到的問題是,如果所有字段都留空,或者甚至一個必填字段都留空,那么數據仍然會傳遞並創建一個新項。

我使用了required: true屬性,認為這將確保輸入數據,然后再沒有數據輸入,將發生錯誤。 雖然這不起作用。

config/initializaers/simple_form.rb文件中, config.browser_validations = true設置為true。

有人知道為什么輸入仍然通過嗎?

簡單的形式:

  <%= simple_form_for @item do |f| %>

  <%= f.collection_select :category_id, Category.all, :id, :name, {promt: "Choose a category" }, input_html: { class: " dropdown-toggle" } %>

  <%= f.input :name, label: "Your Name", required: true, error: 'Your name is required', input_html: { class: "form-control", maxlength: 30} %>

  <%= f.input :title, label: "Item Title", required: true, error: 'Item title is required', input_html: { class: "form-control", maxlength: 50 } %>

  <%= f.input :used?, as: :check_boxes, required: true, label: "Is Your Item Used?" %>

  <%= f.input :price, label: "Item Price", required: true, error: 'Price is required', input_html: { class: "form-control", :placeholder => "$" }  %>

  <%= f.input :description, label: "Item Description", input_html: { class: "form-control" } %>

  <%= f.input :email, label: "Email", required: true, error: 'Email is required', input_html: { class: "form-control", :placeholder => "user@email.com" } %>

  <%= f.input :phone, label: "Phone Number", input_html: { class: "form-control", :placeholder => "+61 --- --- ---", :value => "+61 " } %>

  <%= f.input :suburb, label: "Suburb", required: true, error: 'Suburb is required', input_html: { class: "form-control" } %>

  <%= f.input :image, label: "Upload An Image (Must be less than 2mb)" %>

  <%= f.button :submit %>

<% end %>

物品型號:

class Item < ActiveRecord::Base
belongs_to :category
belongs_to :user
end

物料控制器:

class ItemsController < ApplicationController
before_action :find_item, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, except: [:index, :show]

def show
end

def new
    @item = current_user.items.build
end

def create
    @item = current_user.items.build(items_params)

        if @item.save
            redirect_to @item
        else
            render "New"
        end
end

def edit
end

private

def items_params
    params.require(:item).permit(:name, :title, :price, :description, :used?, :email, :phone, :suburb, :category_id, :image, :search)
end

def find_item
    @item = Item.find(params[:id])
end
end

從simple_form文檔中:

默認情況下,所有輸入都是必需的。 當表單對象的字段附帶狀態驗證時,簡單表單將必填字段和可選字段分開。 出於性能原因,在使用條件選項(例如:if和:unless)的驗證中將跳過此檢測。

您可以在Item模型中添加對狀態的驗證,例如validates :name, presence: true您無需為每個輸入手動添加消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM