首页 > 解决方案 > 在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") %>);" %>

但是,也许有更好的方法,在我的模型中使用方法?

你怎么能做同样的事情?

标签: ruby-on-rails

解决方案


使用 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)并为帮助器方法设置一个更具表现力的名称。


推荐阅读