Derptacos
Derptacos

Reputation: 177

first_or_create causing issues when creating object with non-valid parameters

Good morning,

Trying to find the best way to avoid the current situation I am in so.. I have a class A which has the following attributes a,b,c,d

When create is called on A, I first check to see if an instance of A exists with the following parameters a,b,c.

Now the line I am using to check the database and create if necessary is

@foo = A.where(:a => params[:A][:a], :b => params[:A][:b],:c => params[:A][:c]).first_or_create!

Class A has the following validations for a,b,c

a's length > 3 & < 15
b must be true (checkbox must be checked)
c's length >50 & < 500

When a user is passing in a blank form I will receive errors generated from the above line. I understand that it is caused by the controller attempting to create an object A that does not meet the validations.

Is the best way to go about this using begin rescue end or error checking pre-first_or_create! ?

Upvotes: 0

Views: 507

Answers (1)

sites
sites

Reputation: 21785

From your two options is better begin rescue end so you don't repeat code you already have in model.

Another option is to use first_or_create without exclamation mark, so your code does not raise error, and then you could show errors in view. I would say this is equivalent to begin rescue end because you could show show errors in your view in rescue part.

Upvotes: 1

Related Questions