Ruby on rails约定用于命名日期/时间字段

时间:2013-02-23 08:43:00

标签: ruby-on-rails ruby-on-rails-3 coding-style naming-conventions

我想制作一个这样的脚手架:

rails generate scaffold Job started_at:datetime completed_at:datetime price:decimal paid_at:datetime estimated_completion_at:datetime comment:text

我在日期时间字段中添加了“_at”,因为这似乎是惯例,因为rails timestamp字段对于datetime是“_at”,对于date是“_on”。但这实际上是一个惯例吗?如果我只是“付费”而不是“paid_at”和“completed”而不是“completed_at”,这样可以吗?

我真的想从一开始就做到这一点。我已经用c#编程多年了,但我是ruby on rails的新手。我喜欢所有惯例,我想确保我这样做是正确的'轨道'。

4 个答案:

答案 0 :(得分:30)

我不知道任何特定的rails约定,并且它并不重要,因为在rails中没有任何东西可以关闭datetime字段。我一直使用的约定是带有_at的后缀日期时间列和带有_on的日期列。一天一次地说出来似乎更自然。

答案 1 :(得分:8)

How you name your date and time columns is not an officially stated convention and does not affect the way your code works. However, if you want to go »the Rails way« you should probably follow conventions generally accepted in the rails community.

  • First of all, there is a a community-driven Ruby on Rails style guide, but it doesn't contain any date column naming conventions.

  • One hint are the Active Record timestamp columns, like created_at as @sierrasdetandil noted in their answer.

  • Another way to figure out what some conventions are is by looking at the Rails style guides of popular Rails shops. For example thoughtbot state in their style guide:

  • Name date columns with _on suffixes.
  • Name datetime columns with _at suffixes.
  • Name time columns (referring to a time of day with no date) with _time suffixes.

This will help you find good names for your columns and prevent confusion for other developers. I think this is a good convention to follow, and you might too, as long as you don't have a compelling reason to name your columns differently.

答案 2 :(得分:5)

实际上, 是Rails中的一个约定,用于两个特定时间戳列的名称:created_atupdated_at具有特殊行为。从 Active Record Basics — Ruby on Rails Guides; 2.2 Schema Conventions

  

还有一些可选的列名称将为Active Record实例添加其他功能:

     
      
  • created_at - 自动设置为首次创建记录的当前日期和时间。
  •   
  • updated_at - 每当记录更新时自动设置为当前日期和时间。
  •   
  • ...
  •   

在该页面中没有提及以“_on”结尾的列名。

答案 3 :(得分:1)

它可能不是Rails中的约定,但实际上在日期/日期时间列的末尾追加_at是有意义的。与仅paid相比,paid_at为您提供了使用日期/日期时间对象的概念,而paid也可以是布尔值或字符串,用于说明付款的状态。所以我想这不仅限于Rails。