我有这个由user_id验证的代码。如果category_name存在,则会阻止创建新Object。代码有效,但我不相信这是最好的做法。
def create
@item_category = ItemCategory.new(item_category_params)
@item_category.user_id = current_user.id
search = ItemCategory.where(:name => @item_category.name,:user_id => current_user.user_id)
if search.blank?
respond_to do |format|
if @item_category.save
format.html { redirect_to :back, notice: 'Se ha creado la categoria' }
format.json { render action: 'show', status: :created, location: @item_category }
else
format.html { render action: 'new' }
format.json { render json: @item_category.errors, status: :unprocessable_entity }
end
end
else
respond_to do |duplicate|
duplicate.html { redirect_to @item_category, alert: 'Categoria Repetida' }
duplicate.json { render json: @item_category.errors, status: :unprocessable_entity}
end
end
end
感谢。
答案 0 :(得分:0)
最好将验证放在ItemCategory模型中......
class ItemCategory < ActiveRecord::Base
validates_uniqueness_of :name, :scope => :user_id
...
end