views:

36

answers:

3

I have the following in the view:

            <% unless contact_email.statuses.empty?%>
                (<%= contact_email.statuses.find(:last).status%>) 
             <% end %>

contact_email is an instance of a specific model.

Could I do something like this?

class ContactEmail < ActiveRecord::Base
  attr_accessible :contact_id, :email_id, :status, :subject, :body, :date_created, :date_sent

  def status
    unless contact_email.statuses.empty?
      contact_email.statuses.find(:last).status
    end
  end

end

is there a better way to do this? is there a way to use the || operator for a default if empty?

Basically, I would like to be able to do the following in the View:

<%= contact_email.status =>

IF there is a value, then display it, if not, show nothing.

A: 

You can directly use following

<%= contact_email.statuses.find(:last).status unless contact_email.statuses.empty? %>

OR

#I change methodname as it looks more meaningful
def last_status 
  (self.statuses.empty?)? "defalut string if you want" : self.statuses.find(:last).status 
end

and call it in your view like

   <%= contact_email.last_status %>
Salil
i think she was asking if she could put it in the model since doing it in the view looks dirty and doesn't follow MVC
corroded
A: 

I'm not sure what you're asking. By inspection, it looks like the code you've posted here will do what you want, but can't you just run it and find out? We don't have your full codebase or schema, but you (hopefully) do :P

<%= x %> outputs the value of x.to_s, and nil.to_s is the empty string. The ContactEmail#status method you defined above returns the last status if there is one, otherwise nil. So yes, what you've written will do what you want.

If you want to provide a default status if there isn't one, how about (in the model):

def last_status
  unless contact_email.statuses.empty?
    contact_email.statuses.find(:last).status
  end
end

def status
  last_status || DEFAULT_STATUS
end

DEFAULT_STATUS = "Hello world!"
Sam Stokes
+1  A: 

I would change this

def status
  unless contact_email.statuses.empty?
    contact_email.statuses.find(:last).status
  end
end

to

def status
  return if statuses.empty?
  statuses.find(:last).status
end

This should make the method cleaner and much more easy to understand.

Now in your view you can call as you want

<%= contact_email.status =>
nas
so does return if statuses.empty? mean it returns out of the status method if empty?
Angela
Yes, the status method will return nil if `statuses.empty?` else it will return the last status which is the final statement in the method
nas