Shortcuts in ActiveRecord?

Shortcuts in ActiveRecord?

狼亦尘 发布于 2021-11-26 字数 397 浏览 792 回复 2 原文

Are there any shortcuts in Rails' ActiveRecord that enables you to search by value of a field?

For instance, let's say I have a 'user' who can be active or inactive. Is there a nice way of doing or do I need to do User.find_by_active(1)

Does this also apply to fields that may have many different values, such as a state column? e.g, Ticket.closed?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


陌生 2022-06-07 1 楼

If the active attribute is a boolean column in the database then you can simply call and it will return true or false depending on the value of the boolean.

In the case of the a state column this will not work. However you could create methods for the User model like...

def open?
  true if self.state == "open"

def closed?
  not open?