如何只显示尚未到期的记录(字段)?
在我的应用程序中,我可以添加优惠并为其指定开始和结束日期,优惠显示为部分。如果开始日期是今天或更早的日期并且尚未到达结束日期,我怎样才能只显示它们?
到目前为止我有:
offerpartial
<% if offer.date_from > Date.today && offer.date_to < Date.today %>
<div class="offer_partial">
<div class="offer_title">
<%= offer.title %>
</div>
<div class="offer_body">
<%= offer.body %>
</div>
</div>
<% end %>
但这给出了一个未定义的方法“>”对于 nil:NilClass 错误。
在视图中进行这些检查是否可以?
非常感谢您的帮助!
In my app I can add offers and give them a start and end date, the offers are displayed as partials. How can I go about only displaying them if the start date is todays date or earlier and the end date has not yet been reached?
So far I have:
offer partial
<% if offer.date_from > Date.today && offer.date_to < Date.today %>
<div class="offer_partial">
<div class="offer_title">
<%= offer.title %>
</div>
<div class="offer_body">
<%= offer.body %>
</div>
</div>
<% end %>
But this gives a undefined method `>' for nil:NilClass error.
Is it even ok to do these kind of checks in the view?
Thanks very much for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先要回答第二个问题,不,您应该通过控制器中的查询构建 Offer 模型的集合,从而使视图仅迭代该集合并呈现 HTML。
另外,if 块不会执行您想要的操作。您说的是“今天的日期或更早的日期”,但您正在检查今天的日期或更晚的日期。看来你把逻辑搞反了。
您收到的错误意味着 date_from 为零。您正在验证这些字段还是允许它们具有零值?
这就是我设置该集合的方式:
在控制器中:
在视图中:
希望这会有所帮助。
To answer your second question first, no, you should build a collection of the Offer models through a query in the controller, thereby leaving the view to just iterate through that collection and render the HTML.
Also, the if block doesn't do what you want it to. You said "Today's date or earlier", but you're checking for today's date or later. It seems that you've inverted the logic.
The error you're getting means that date_from is nil. Are you validating those fields or are they allowed to have a nil value?
This is how I would set that collection up:
In the controller:
In the view:
Hope this helps.