4

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

1 Answer 1

10

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?)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, both options worked perfectly. I have to read up on the differences between each and collect.
There's not much to read up about... each just runs the block for each element of the Array, map or collect runs the block for each element of the Array AND collects the return value for each iteration of the block into a new Array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.