Are there any 'protected' names you should

2019-08-13 22:27发布

This question already has an answer here:

I'm new to Rails and I just wondered if there were any protected names you should avoid using in your models? For example, would the following be valid:

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

      t.timestamps
    end
  end
end

I realise has probably isn't a great name for a property, but it's a pure example.

Edit: All the responses were good, but I've chosen my accepted answer because it contains a link to a huge list of protected attributes.

4条回答
The star\"
2楼-- · 2019-08-13 22:47

I can remember only two:

  1. type, because Rails treats this property as a type of parent object in polymorphic objects.
  2. order and any other SQL commands/statements/etc., because Rails generating SQL queries is using them and usually an exception occurs.
查看更多
ら.Afraid
3楼-- · 2019-08-13 23:05

Avoid class names, if they are defined:

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

Avoid column names within this list:

  • id - Reserved for primary keys
  • lock_version
  • type - single table inheritance and must contain a class name
  • table_name_count - Reserved for counter cache
  • position - Reserved for acts_as_list
  • parent_id - Reserved for acts_as_tree
  • lft - Reserved for acts_as_nested_set
  • rgt - Reserved for acts_as_nested_set
  • quote - Method in ActiveRecord::Base which is used to quote SQL
  • template
查看更多
爷的心禁止访问
5楼-- · 2019-08-13 23:06

I had an issues with an external db and a column named "hash". The offending column can be ignored in this manner:

class SomeClass < ActiveRecord::Base
  class << self # Class methods
    alias :all_columns :columns 

    def columns 
      all_columns.reject {|c| c.name == 'hash'} 
    end 
  end 
end
查看更多
登录 后发表回答