views:

72

answers:

2

I have a helper method which checks whether the collection of objects is empty? If not then it checks each one to make sure that the the existing event_id is not the @current_event.id.

Here is my crack at it:

def build_answers(question)
  if question.answers.empty?
    return question.answers.build
  else
    question.answers.each do |a|
      if a.event_id != @current_event.id
        return question.answers.build
      end
    end
  end
end

Update: This helper method sets the form to build new children objects if the conditions pass. I've updated the example above. btw, it doesn't need to be a single line. I just wanted something cleaner than what I have above.

+1  A: 

Without knowing what you're actually doing inside the blocks, it's difficult to give the best solution.

For the most part, all you could really do is select before executing the logic on the filtered collection, rather than testing the logic in the block.

e.g.

uncurrent_answers = questions.answers.select{|a| a.event_id != @current_event.id}
uncurrent_answers.each do |a|
  #do whatever
end

IMHO it's a little bit neater, and perhaps more rubyish..

Jeriko
The select block is what I was looking for (I didn't know what it was called). map and other methods just didn't work (obviously). Thanks!
Nate Bird
@Nate For future reference, you might want to check out all the other methods that are in [Enumerable](http://ruby-doc.org/core/classes/Enumerable.html).
mikej
Thanks for the link.
Nate Bird
+1  A: 

Well, I don't know why would you want to put conditions into a single line, but the else block could be rewritten into this:

question.answers.select {|answer| answer.event_id != @current_event.id }.each
    {|ans| #.. logic with answer here }  
Tumas
I gave you a point for coming up with the select option first. Just what I needed. Thanks!
Nate Bird