views:

34

answers:

2

While creating a new object i am getting ActiveRecord::RecordNotSaved error on before_save.

But i want to fetch the proper message other than ActiveRecord::RecordNotSaved error message.

How may i fetch the proper error message and pass it to the rescue?

begin

  #some logic
  raise unless object.save!
rescue ActiveRecord::RecordNotSaved => e
  # How may fetch proper message where my object is failing here ..
  # like object.errors.message or something like that.
end
A: 

Why raise the exception and not just check if save or not ?

unless object.save
  object.errors
end
shingara
@shingara I am reading csv files and inserting data into my tables. And i am using transaction so i have to use the raise to fetch the errors. That's the need of my logic.
krunal shah
A: 
begin
  #some logic
  raise unless @object.save!
rescue ActiveRecord::RecordNotSaved => e
  @object.errors.full_messages
end

Updated

begin
  #some logic
  @object.save!
rescue ActiveRecord::RecordNotSaved => e
  @object.errors.full_messages
end
krunal shah
`raise` doesn't do anything here, because `@object.save!` already raises an error. Remove the `raise unless` and it will still work.
zetetic
@zetetic Yes that's working thanks.
krunal shah