Rails 5不会因self.errors.add(:base)而引发错误

时间:2017-06-10 14:18:11

标签: ruby-on-rails ruby devise ruby-on-rails-5

我有一个名为Thing的模型和一个名为Things的控制器。

我跟着this tutorial尝试设置用户可以创建的最大Things数量。

这是警告:终端正在发出警告(不是一个大问题)DEPRECATION WARNING: Passing an argument to force an association to reload is now deprecated and will be removed in Rails 5.1. Please call "reload" on the result collection proxy instead.我该怎么办才能让它消失?

问题在于:行self.errors.add(:base, "Exceeded Things Limit")未在视图中显示警告或通知。我怎么做到这一点?这不是创造一个新的东西(因为我达到了2的最大限制)这是好的,但它只是重新加载一个新的形式,这将是用户体验的可怕。

我正在使用Rails 5和Devise。

这是我的Thing模型:

class Thing < ApplicationRecord
 belongs_to :user
 validate :thing_count_within_limit, :on => :create
 attr_accessor :validation_code, :flash_notice

 def self.search(search)
      if search
           where("zipcode LIKE ?", "%#{search}%")
      else
           all
      end
 end

 def thing_count_within_limit
      if self.user.things(:reload).count >= 2
           self.errors.add(:base, "Exceeded Things Limit")
      end
 end
end

这是我的Things控制器:

class thingsController < ApplicationController
 before_action :find_thing, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user_first, only: [:edit, :update, :destroy]
 before_action :authorized_pilot, only: [:edit, :update, :destroy, :profile]

 def index
      @things = Thing.all.order("created_at ASC")
      @things = Thing.search(params[:search])
 end

 def new
      @thing = current_user.things.build
 end

 def create
      @thing = current_user.things.build(thing_params)
      if @thing.save
           redirect_to @thing
      else
           render "new"
      end
 end

 def profile
      @things = Thing.where(user_id: current_user)
 end

 def show
 end

 def edit
 end

 def update
      if @thing.update(thing_params)
           redirect_to @thing
      else
           render "edit"
      end
 end

 def destroy
      if @thing.destroy
           redirect_to root_path
      else
           redirect_to @thing
      end
 end

 private
      def thing_params
           params.require(:thing).permit(:title, :description, :image).merge(zipcode: current_user.zipcode)
      end

      def find_thing
           @thing = thing.find(params[:id])
      end

      def authenticate_user_first
           if current_user != thing.find(params[:id]).user
                redirect_to @thing
           else
           end
      end
 end

有人可以帮忙吗?非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

有两件事并没有相互联系。

首先,有弃用警告。因为它只是一个警告,而不是错误,您可以选择忽略它。如果要删除警告,只需按照其说明更改此行

即可
if self.user.things(:reload).count >= 2

self.user.things.reload.count >= 2

秒,你的代码就像预期的那样工作。 Rails验证不会引发任何错误,但它们会向对象添加错误消息。只需确保向用户显示错误。要显示您添加到:base的错误,请在new.html.erb视图中添加以下内容:

<% if @thing.errors[:base].any? %>
  <div class="error_message">
    <%= @thing.errors.full_messages_for(:base).to_sentence %>
  </div>
<% end %>