Rails'要求:true'不能完全运行

时间:2016-07-27 21:19:30

标签: ruby-on-rails ruby

我有一个带有分组集合选择的simple_form和两个输入字段。我有一个必需:两个字段都是true,但它仍然允许空输入。字段名称旁边会出现小“必需”星号,但就是这样。有什么方法可以阻止空输入通过表单吗?

new.rb

<h1>New Article</h1>

<%= render 'form', article: @article %>

<%= link_to 'Back', articles_path(category_id: params[:category_id]) %>

_form.rb

<%= simple_form_for(article, html: {class: 'form-vertical'}) do |f| %>
  <% if article.errors.any? %>
    <div id="error_explanation">
      <h4><%= pluralize(article.errors.count, "error") %> prohibited this article from being saved:</h4>

      <ul>
      <% article.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">

  <%# field being selected, parent collection, subcollection, displayed, key, value %>
  <%= f.grouped_collection_select :subcategory_id, Category.all,:subcategories,:name, :id,:name, {required: true} %>
    <%= f.input :title, required: true %>
    <%= f.input :content, input_html: { rows: 20 }, required: true%>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

articles_controller.rb

class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  # GET /articles
  # GET /articles.json
  def index
    if params[:category_id].blank? && params[:subcategory_id].blank?
      @articles = Article.all.order("created_at DESC")
    elsif params[:subcategory_id].blank?
      @articles = Article.where(category_id: params[:category_id])
    else
      @articles = Article.where(subcategory_id: params[:subcategory_id]).order("created_at DESC")
    end
  end

  # GET /articles/1
  # GET /articles/1.json
  def show
  end

  # GET /articles/new
  def new
    @article = Article.new
  end

  # GET /articles/1/edit
  def edit
  end

  # POST /articles
  # POST /articles.json
  def create
    @parameters = article_params
    @parameters[:category_id] = Subcategory.find(@parameters[:subcategory_id]).category_id
    @article = Article.new(@parameters)

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

  # PATCH/PUT /articles/1
  # PATCH/PUT /articles/1.json
  def update
    respond_to do |format|
      if @article.update(article_params)
        format.html { redirect_to @article, notice: 'Article was successfully updated.' }
        format.json { render :show, status: :ok, location: @article }
      else
        format.html { render :edit }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /articles/1
  # DELETE /articles/1.json
  def destroy
    @article.destroy
    respond_to do |format|
      format.html { redirect_to root_path, notice: 'Article was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_article
      @article = Article.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def article_params
      params.require(:article).permit(:title,:content,:subcategory_id)
    end
end

3 个答案:

答案 0 :(得分:1)

根据 Rails 的简单文档。你的模型应该是这样的(假设我想验证 first_name last_name 和 compnay_name 的存在):

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  validates :company_name, presence: true
  validates :first_name, presence: true
  validates :last_name, presence: true
end

现在你准备好了,presence: true 将在将数据保存到数据库之前验证数据。一个好的做法是也向前端添加验证。这是添加 require: true 到您的 form_for 助手。

<div class="field">
   <%= f.label :last_name %><br />
   <%= f.text_field :last_name, autofocus: true, required: true ,autocomplete: "email", class: "border p-3 w-100 my-2" %>
</div>

答案 1 :(得分:0)

您需要使用验证,逻辑在模型内部完成。 请务必阅读并承认ActiveRecord Validations Guide,因为它会为您节省大量时间。 从指南中获取的示例:

class Person < ApplicationRecord
  validates :name, presence: true
end



Person.create(name: "John Doe").valid? # => true
Person.create(name: nil).valid? # => false

基本上,当保存对象时,它会运行验证,如果它无效,它将使用消息填充errors变量。

答案 2 :(得分:0)

简单表单文档说明......

  

默认情况下,所有输入都是必需的。当表单对象存在时   附加到其字段的验证,简单表单告诉必需和   可选字段分开。出于性能原因,这种检测是   跳过使用条件选项的验证,例如   :if和:除非。

这意味着你需要做的就是添加到你的model / article.rb文件中

class Article < ActiveRecord::Base

  validates :title, presence: true
  validates :content, presence: true