I am trying to figure out how to write a conditional statement that will execute only if a specified variable is not empty. Right now my view looks like this: <dt>Building Regulations</dt> <% for link in @cat1 %> <dd><a href="<%= link.url %>"><%= link.title %></a></dd> <% end %> Action: @cat1 = Link.find(:all, :conditions => "category = ''1'' ") But I want it to be something like this: <% if @cat1 != "" %> <dt>Building Regulations</dt> <% for link in @cat1 %> <dd><a href="<%= link.url %>"><%= link.title %></a></dd> <% end %> <% end %> the "<% if @cat1 != "" %>" is the part I cannot figure out how to say. Thanks. -- Posted via http://www.ruby-forum.com/.
How about: <% unless @cat1.size == 0 %> Lindsay -- Posted via http://www.ruby-forum.com/.
On May 2, 2006, at 01:35 PM, ben wrote:> Action: > @cat1 = Link.find(:all, :conditions => "category = ''1'' ")Key point, when you do a find :all, what you get back is an Array. So what you need to test for is whether the array is empty.> But I want it to be something like this: > > <% if @cat1 != "" %> > > <dt>Building Regulations</dt> > <% for link in @cat1 %> > <dd><a href="<%= link.url %>"><%= link.title %></a></dd> > <% end %> > > <% end %> > > the "<% if @cat1 != "" %>" is the part I cannot figure out how to say.Change that line to: "<% unless @cat1.empty? %>". This way you are telling Ruby to evaluate the block only when @cat1 has items to process. Of course, you don''t really need to do this in this way. I would actually eliminate the unless block altogether. The "for link in @cat1" loop statement will simply not fire if @cat1 is empty. So that just leaves the Building Regulations line. I would probably change that to: <%= @cat1.empty? ? "" : "<dt>Building Regulations</dt>" %> And if you''re OK with that, the next step would be to replace the for loop with: <%= render :partial=>"link", :collection => @cat %> That will really clean up your view code. -Brian
2006/5/2, Lindsay Boyd <lindsay.boyd@ntlworld.com>:> > the "<% if @cat1 != "" %>" is the part I cannot figure out how to say. > > How about: > > <% unless @cat1.size == 0 %>How about : <% unless @cat1.empty? -%> ? -- Jean-Fran?ois. -- ? la renverse.
On May 2, 2006, at 01:59 PM, Jean-Fran?ois wrote:> 2006/5/2, Lindsay Boyd <lindsay.boyd@ntlworld.com>: > >> > the "<% if @cat1 != "" %>" is the part I cannot figure out how >> to say. >> >> How about: >> >> <% unless @cat1.size == 0 %> > > How about : <% unless @cat1.empty? -%> ?In fact, I would say that you would always use this form, over checking for a length of zero. Checking for Array length is something you do when you need to do something numeric with that value. If you want to know if an Array is empty, that''s asking the object for a boolean value, not a number... -Brian