Reputation: 235
I am working with rails4. In my controller i have parsing json and storing into database. My controller is like this,
def store
@data.each do |invite|
MemberInvitation.create!(:email => invite['email'])
end
end
This works fine....
As we know create will automatically call validators
but If the validation fails how to display the error messages using json render. Because i am defining validations in MemberInvitation model.
How to handle this scenario!!!
I wanted to render error messages in json format if error raised!!!
Upvotes: 0
Views: 36
Reputation: 115521
A quick way to get a report is:
def store
errors = []
@data.each do |invite|
new_member = MemberInvitation.new(:email => invite['email'])
errors.push(new_member) unless new_member.save
end
if errors.empty?
#everything went fine
else
# you have all members with issues in the array
# I advise you to create your json yourself
end
end
Upvotes: 2