简体   繁体   中英

Rendering Error Messages in Custom Controller Action

I've added the following to my controller's create action:

 def create 
   BatchUser.mass_insert_v2(params[:batch_user][:batch_name], params[:batch_user]  [:batch_description], params[:batch_user][:quantity])
  redirect_to batch_users_path
 end

'mass_insert_v2', in my BatchUser model, starts like this:

 def self.mass_insert_v2(batch_name, batch_description, quantity)
  @batch_create = BatchUser.create! :batch_name => batch_name, :batch_description => batch_description
   ...
 end

And then goes on to create X user accounts with random usernames and passwords. I've chosen this route because I found raw sql insertion to be faster than using activerecord on its own.

The problem I have is that I'm struggling to render my error messages. For example, batch_name must be present and unique.

I do get an error screen:

 ActiveRecord::RecordInvalid in BatchUsersController#create

But no errors show.

Previously, I've had this check in my controller:

 respond_to do |format|
   if @batch_user.save
   ....
   else
   ....

But that doesn't seem to work anymore. What can I do to display the errors on the page??

The create! (create with bang!) will throw an exception if the object fails validations. Unless you are planning on catching this exception and handling you might be better off just using create and then checking if the object was created successfully (has an id) and/or has errors.

There are several railsy ways of handling the finding and rendering error messages so you can experiment. However, knowing the following along with the important note above will help get you on track I think:

 @batch_user = BatchUser.create(attr_hash) #will give you an object to work with instead of throwing an exception.

If you have an existing object:

 @batch_user.valid? #will trigger the validations only and set the object's errors attribute with any relevant data and return a boolean value.

 @batch_user.errors #gives you access to the error data (in 3.1 ActiveModel::Errors object)

As far as actually rendering the errors, like I said there are several options. I prefer either putting those error messages (obj.errors.full_messages) in the flash or using something like the dynamic_form plugin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM