如何将逻辑放入视图、模型中的范围或方法中?
我的视图中有以下内容:
<% unless contact_email.statuses.empty?%>
(<%= contact_email.statuses.find(:last).status%>)
<% end %>
contact_email 是特定模型的实例。
我可以做这样的事情吗?
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
有更好的方法吗?有没有办法使用 ||如果为空,则默认运算符?
基本上,我希望能够在视图中执行以下操作:
<%= contact_email.status =>
如果有值,则显示它,如果没有,则不显示任何内容。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会将其更改
为
这应该使该方法更清晰且更易于理解。
现在在您看来您可以随意拨打电话
I would change this
to
This should make the method cleaner and much more easy to understand.
Now in your view you can call as you want
您可以直接使用以下
OR
并在您的视图中调用它,例如
You can directly use following
OR
and call it in your view like
我不确定你在问什么。通过检查,您在此处发布的代码似乎可以实现您想要的功能,但是您不能运行它并找出答案吗?我们没有您的完整代码库或架构,但您(希望)这样做 :P
<%= x %>
输出x.to_s
的值,并且nil.to_s
是空字符串。如果有的话,您上面定义的ContactEmail#status
方法将返回最后一个状态,否则nil
。所以是的,你所写的将达到你想要的效果。如果您想提供默认状态(如果没有),可以(在模型中):
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 ofx.to_s
, andnil.to_s
is the empty string. TheContactEmail#status
method you defined above returns the last status if there is one, otherwisenil
. 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):