在Rails模型中是否应该避免使用任何“受保护”的名称?

我是Rails的新手,我只是想知道你的模型中是否应该避免使用任何受保护的名称? 例如,以下内容是否有效:

class CreateModel < ActiveRecord::Migration def change create_table :model do |t| t.string :hash t.integer :count t.timestamps end end end 

我意识到可能不是一个属性的好名字,但它是一个纯粹的例子。

编辑:所有答案都很好,但我选择了我接受的答案,因为它包含一个巨大的受保护属性列表的链接。

我亲自遇到了一个问题,我将模型record命名为:

除此之外:

避免使用类名,如果已定义:

 !!defined? Class # => true !!defined? Model # => false 

避免在此列表中使用列名:

  • id – 保留主键
  • lock_version
  • type – 单表inheritance,必须包含类名
  • table_name_count – 保留用于计数器缓存
  • position – 为acts_as_list保留
  • parent_id – 为acts_as_tree保留
  • lft – 为acts_as_nested_set保留
  • rgt – 为acts_as_nested_set保留
  • quote – ActiveRecord :: Base中用于引用SQL的方法
  • 模板

我只记得两个:

  1. type ,因为Rails将此属性视为多态对象中的一种父对象。
  2. order和任何其他SQL命令/语句/等,因为生成SQL查询的Rails正在使用它们,通常会发生exception。

我遇到了外部数据库和名为“hash”的列的问题。 可以通过以下方式忽略违规列:

 class SomeClass < ActiveRecord::Base class << self # Class methods alias :all_columns :columns def columns all_columns.reject {|c| c.name == 'hash'} end end end