what is the proper way to loop through a list in a rails view (assuming that you need to check if it is empty or not)
my_list.each do | an_item | puts "#{an_item}" end
If the list is empty nothing is printed.
Paul Hoehne wrote:
my_list.each do | an_item | puts "#{an_item}" end
If the list is empty nothing is printed.
should i return my lists from the model?
<%- @records.each do |record| -%> here you handle each record, doing what has to be done <%- end -%>
If @records is an empty array or other Enumerable, then the inside of the loop will never be executed. If @records is nil, you'll throw an error.
If you just want to remove all empty elements in your array, before looping, you can just do this in your controller:
@records.compact!
This removes all nil elements. Then when you loop through it in the view, you only get real records.
Scenario 1:
Brent Miller wrote:
<%- @records.each do |record| -%> here you handle each record, doing what has to be done <%- end -%>
If @records is an empty array or other Enumerable, then the inside of the loop will never be executed. If @records is nil, you'll throw an error.
If you just want to remove all empty elements in your array, before looping, you can just do this in your controller:
@records.compact!
This removes all nil elements. Then when you loop through it in the view, you only get real records.
so should I always do a nil check on @records before I loop through the records?
If you use a find(:all, ...) method you will get back a collection of an empty collection. If you navigate a relationship you will get a collection or an empty collection. Generally, in rails, methods that return a collection will return an empty collection, not nil.
If, however, you have code like:
def some_action @thing = MyModel.find(params[:id]) if @thing.some_test @list_of_stuff = @thing.children end end
Then you would need to test @list_of_stuff to see if it's nil. But that's probably bad form.
Paul Hoehne wrote:
If you use a find(:all, ...) method you will get back a collection of an empty collection. If you navigate a relationship you will get a collection or an empty collection. Generally, in rails, methods that return a collection will return an empty collection, not nil.
If, however, you have code like:
def some_action @thing = MyModel.find(params[:id]) if @thing.some_test @list_of_stuff = @thing.children end end
Then you would need to test @list_of_stuff to see if it's nil. But that's probably bad form.
thanks guys. I found that my problem was that i was using find_all_by incorrectly and it was returning nil.