【问题标题】:Rails CMS Casein and Validation of UniquenessRails CMS 酪蛋白和唯一性验证
【发布时间】:2016-01-21 22:07:12
【问题描述】:

您好,当我尝试向我的 Rails Casein(Rails 的 CMS)控制器添加唯一性验证时,我一直收到错误消息。我不确定我做错了什么,但我一直收到此错误:

ActionController::RoutingError - 未定义的方法“验证” 酪蛋白::ItemsController:类:

我使用酪蛋白支架生成以下代码,只在第 3 行添加了validates :order, uniqueness: true。如何使:order(整数字段类型)在我的数据库中是唯一的?

# Scaffolding generated by Casein v5.1.1.5

module Casein
  class ItemsController < Casein::CaseinController
    validates :order, uniqueness: true


    ## optional filters for defining usage according to Casein::AdminUser access_levels
    # before_filter :needs_admin, :except => [:action1, :action2]
    # before_filter :needs_admin_or_current_user, :only => [:action1, :action2]

    def index
      @casein_page_title = 'Items'
        @items = Item.order(sort_order(:title)).paginate :page => params[:page]
    end

    def show
      @casein_page_title = 'View item'
      @item = Item.find params[:id]
    end

    def new
      @casein_page_title = 'Add a new item'
        @item = Item.new
    end

    def create
      @item = Item.new item_params

      if @item.save
        flash[:notice] = 'Item created'
        redirect_to casein_items_path
      else
        flash.now[:warning] = 'There were problems when trying to create a new item'
        render :action => :new
      end
    end

    def update
      @casein_page_title = 'Update item'

      @item = Item.find params[:id]

      if @item.update_attributes item_params
        flash[:notice] = 'Item has been updated'
        redirect_to casein_items_path
      else
        flash.now[:warning] = 'There were problems when trying to update this item'
        render :action => :show
      end
    end

    def destroy
      @item = Item.find params[:id]

      @item.destroy
      flash[:notice] = 'Item has been deleted'
      redirect_to casein_items_path
    end

    private

      def item_params
        params.require(:item).permit(:title, :caption, :url, :description, :order, :image)
      end

  end
end

感谢大家的时间和帮助!

【问题讨论】:

  • 如果您想确保它在在您的数据库中是唯一的,那么您应该为该列设置数据库规则。这是真正确保数据库唯一性的唯一方法
  • 如果我的数据库已经有:order 作为现有列,那么让它在数据库中独一无二的最佳方法是什么? rails g migration add_index :item, [:order], :unique =&gt; true??如果这确实有效,如果我尝试输入数据库中已经存在的:order,rails 会抛出错误吗?

标签: ruby-on-rails ruby validation


【解决方案1】:

我不知道那个 gem,但是在 rails 中,验证属于定义模型的文件,而不是控制器。

从您提到的 gem 的这行代码来看: https://github.com/russellquinn/casein/blob/master/app/models/casein/admin_user.rb#L26 它应该以与酪蛋白相同的方式工作。 (请注意,该文件定义的是模型,而不是控制器)。

【讨论】:

  • 感谢您的帮助!完全白痴了一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
相关资源
最近更新 更多