【发布时间】: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 => true??如果这确实有效,如果我尝试输入数据库中已经存在的:order,rails 会抛出错误吗?
标签: ruby-on-rails ruby validation