How do I put logic in a View a scope or method in a Model?
I have the following in the view:
<% unless contact_email.statuse开发者_JS百科s.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.
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 =>
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 %>
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!"
精彩评论