Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use valid? method on an array in rails 3

I am working on an app in rails 3.

I have several records that i want to save to my database. I am trying to make sure that all the objects in an array (the records are stored in an array) are valid before saving. The Owner model validates the presence of name and email. In the rails console, I have tried the following:

@owner = Array.new
=> []

@owner[0] = Owner.new (name:"peter", email:"[email protected]")
=> returns object

@owner[1] = Owner.new (name:"fred", email:"[email protected]")
=> returns object

@owner[2] = Owner.new (name:"", email:"")
=> returns object

@owner[0].valid?
=> true

@owner[1].valid?
=> true

@owner[2].valid?
=> false

@owner.each { |t| t.valid? }
=> returns an array like this: [object1, object2, object3]. I would expect something like this instead: [true,true,false]

I dont understand why the .valid? method works fine if I individually check the elements of the array using @owner[i], but doesnt work correctly if I'm using .each to iterate through the array. Anybody know what might be the problem?

What I am trying to do is achieve something like this:

(@owner.each { |t| t.valid? }).all?

To make sure that each record is valid, then I can proceed to save them.

Thanks

like image 215
David Hemmat Avatar asked Dec 26 '22 02:12

David Hemmat


1 Answers

Each does not return an array of valid? values. You probably want either:

(@owner.collect { |t| t.valid? }).all?

or

(@owner.all? { |t| t.valid? })

The examples can also be written as:

@owner.collect(&:valid?).all?

or

@owner.all?(&:valid?)
like image 98
patrickmcgraw Avatar answered Dec 28 '22 15:12

patrickmcgraw