ruby-on-rails - 在rails中分解此代码的最佳方法是什么
问题描述
我想分解这段代码(if/else)。
在第一种方式中,我做这样的事情:
<% @pois.each_with_index do |poi, i| %>
<div class="card-item">
<% if poi.poitable.sleep_images.blank? %>
<div class="card-sleep-thumb" style="background-image: url(<%= cl_image_path("comingsoon.jpg", :width=>600, :crop=>"scale") %>);">
<% else %>
<div class="card-sleep-thumb" style="background-image: url(<%= cl_image_path(poi.poitable.sleep_images.first.image, :width=>600, :crop=>"scale") %>);">
<% end %>
在第二种方式中,我尝试另一种这样的想法:
<div class="card-sleep-thumb" style="background-image: url(<%= if poi.poitable.sleep_images.blank? ? cl_image_path("comingsoon.jpg", :width=>600, :crop=>"scale" : cl_image_path(poi.poitable.sleep_images.first.image, :width=>600, :crop=>"scale") %>);" %>
但是,也许有更好的方法,在我的模型中使用方法?
你怎么能做同样的事情?
解决方案
使用 Helper 方法
class SomeModelHelper
def some_method_name(poi)
if poi.poitable.sleep_images.blank?
cl_image_path("comingsoon.jpg", :width=>600, :crop=>"scale")
else
cl_image_path(poi.poitable.sleep_images.first.image, :width=>600, :crop=>"scale")
end
end
end
// in the view
<div class="card-sleep-thumb" style="background-image: url(<%= some_method_name(poi).html_safe %>);" %>
当然,您应该使用与poi
该类关联的帮助器(例如PoiHelper
,如果该类被调用Poi
)并为帮助器方法设置一个更具表现力的名称。
推荐阅读
- java - 我正在尝试使用 Android 中的 JobIntentService 上传多个文件
- mongodb - 从 Google 平台上托管的 Docker 应用程序连接到 MongoDB Atlas 的问题
- python - 我试图将我的函数转换为 lambda
- vue.js - 了解如何使用 Bootstrap vue 正确添加分页
- python - 想要从 csv 文件末尾删除引号 (" ")
- python - 如何使用双括号实现 2D 访问
- lua - 为什么此更改 gui 代码不适用于 Roblox Studio?
- java - 获取从另一个类继承的类的数量
- python-3.x - 解析字节格式的 http 响应
- vuejs2 - Vue2传单强制地图具有父容器的100%高度