条件类名和文本 (Rails)

Conditional classname and text (Rails)

我是 Rails 的新手,正在尝试一些基本的东西,比如条件 类。

在 'show' 视图中,我有一个元素可以根据库存情况更改样式,而且文本也会相应更改。

人们一直在说控制器应该越小越好,但是将这个条件放在视图中也感觉很脏。这真的是最好的方法吗?

当前控制器:

def show
  @tyre = Tyres::Tyre.find_by_id(params[:id])

  if @tyre.in_stock
    @availability = I18n.t("products.filter.other.in_stock")
    @availability_class = 'i-check-circle color--success'
  else
    @availability = I18n.t("products.filter.other.not_in_stock")
    @availability_class = 'i-cross-circle color--important'
  end
end

编辑:

控制器:

def show
  @tyre = Tyres::Tyre.find_by_id(params[:id])

  if @tyre.in_stock
    @availability_append = ".in_stock"
  else
    @availability_append = ".not_in_stock"
  end

  @availability = I18n.t("products.filter.other#{@availability_append}")
end

查看:

.xs-12.description__status
  %i{class: (@tyre.in_stock? ? 'i-check-circle color--success' : 'i-cross-circle color--important')}
  = @availability

您可以清理您的 控制器 tyres_controller.rb (我想)方法,

def show
 @tyre = Tyre.find(params[:id]) # I believe you have a model named 'tyre'
end

然后,在您的myproject/app/helpers/中将有一个名为tyres_helper.rb的文件。将以下代码放在那里,

def tyre_availability(tyre)  # it'll return an array with two values, first one is class name, second one is localized value
  if tyre.in_stock
    return 'i-check-circle color--success', I18n.t("products.filter.other.in_stock")
  else 
    return 'i-cross-circle color--important', I18n.t("products.filter.other.not_in_stock")
  end
end

并且,在视图中您可以使用,

.xs-12.description__status
  %i{:class => tyre_availability(@tyre)[0]}
  = tyre_availability(@tyre)[1]