Ruby on Rails - 从模型或控制器而不是视图将 TRUE 更改为 ACTIVE

Ruby on Rails - Changing TRUE to ACTIVE from model or controller instead of view

在我的 companies 数据库中,我有一个 status 列 - boolean (真或假) .是否可以将 true 更改为 active & false 更改为 inactive 来自模型或控制器而不是视图模板。

这是我目前在我的视图模板中使用的:

- if company.status == true
  %p Active
- else
  %p Inactive

我觉得这些只是不必要的条件,我正在寻找更清洁的方法。

在您的 Company 模型中,定义一个这样的函数。

def get_status
  return self.status ? "Active" : "Inactive"
end

在你看来,你可以简单地做到这一点。

<%= company.get_status %>

Is it possible to change true to active & false to inactive from model or controller instead of view templates.

是有可能

您可以在模型级别编写 instance method 以使视图代码 DRY

之后,我们可以用更抽象的方式写成!!!

def get_status
 status ? "Active" : "Inactive"
end

先前答案的附录:在模型中放置视图关注点不是最佳实践 - 它违反了 SRP。当然,您不会因为那个小罪而被闪电击中,但是您应该意识到这一点。

另外一种选择是将此基本逻辑保留在视图中,就像使用常见的 one-liner :

%p= company.status ? "Active" : "Inactive"

或者最后把它放在一个助手中:

%p= boolean_to_activity( company.status )

# ... in helpers/some_helper.rb

def boolean_to_activity status
  status ? "Active" : "Inactive"
end