【问题标题】:Reserved names with ActiveRecord modelsActiveRecord 模型的保留名称
【发布时间】:2012-12-06 18:20:39
【问题描述】:

我非常重视命名,因此我非常努力地为我的 ActiveRecord 模型命名。但是,我经常想出一个名称,它与数据库或 Ruby 或 Rails 中的保留名称有一些冲突。模型或字段名称,例如 setgroup。有时问题也不会立即显现出来。是否有一个我们不能在模型名称中使用的名称列表和一个字段名称列表?

【问题讨论】:

  • this site has some of them 但是我一直没能找到一个完整的列表。可能是一些很酷的东西来创建一个 wiki。

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2 active-record-query


【解决方案1】:

保留字列表

ADDITIONAL_LOAD_PATHS
ARGF
ARGV
ActionController
ActionView
ActiveRecord
ArgumentError
Array
BasicSocket
Benchmark
Bignum
Binding
CGI
CGIMethods
CROSS_COMPILING
Class
ClassInheritableAttributes
Comparable
ConditionVariable
Config
Continuation
DRb
DRbIdConv
DRbObject
DRbUndumped
Data
Date
DateTime
Delegater
Delegator
Digest
Dir
ENV
EOFError
ERB
Enumerable
Errno
Exception
FALSE
FalseClass
Fcntl
File
FileList
FileTask
FileTest
FileUtils
Fixnum
Float
FloatDomainError
GC
Gem
GetoptLong
Hash
IO
IOError
IPSocket
IPsocket
IndexError
Inflector
Integer
Interrupt
Kernel
LN_SUPPORTED
LoadError
LocalJumpError
Logger
Marshal
MatchData
MatchingData
Math
Method
Module
Mutex
Mysql
MysqlError
MysqlField
MysqlRes
NIL
NameError
NilClass
NoMemoryError
NoMethodError
NoWrite
NotImplementedError
Numeric
OPT_TABLE
Object
ObjectSpace
Observable
Observer
PGError
PGconn
PGlarge
PGresult
PLATFORM
PStore
ParseDate
Precision
Proc
Process
Queue
RAKEVERSION
RELEASE_DATE
RUBY
RUBY_PLATFORM
RUBY_RELEASE_DATE
RUBY_VERSION
Rack
Rake
RakeApp
RakeFileUtils
Range
RangeError
Rational
Regexp
RegexpError
Request
RuntimeError
STDERR
STDIN
STDOUT
ScanError
ScriptError
SecurityError
Signal
SignalException
SimpleDelegater
SimpleDelegator
Singleton
SizedQueue
Socket
SocketError
StandardError
String
StringScanner
Struct
Symbol
SyntaxError
SystemCallError
SystemExit
SystemStackError
TCPServer
TCPSocket
TCPserver
TCPsocket
TOPLEVEL_BINDING
TRUE
Task
Text
Thread
ThreadError
ThreadGroup
Time
Transaction
TrueClass
TypeError
UDPSocket
UDPsocket
UNIXServer
UNIXSocket
UNIXserver
UNIXsocket
UnboundMethod
Url
VERSION
Verbose
YAML
ZeroDivisionError
@base_path
accept
Acces
Axi
action
attributes
application2
callback
category
connection
database
dispatcher
display1
drive
errors
format
host
key
layout
load
link
new
notify
open
public
quote
render
request
records
responses
save
scope
send
session
system
template
test
timeout
to_s
type
URI
visits
Observer

数据库字段名称

created_at
created_on
updated_at
updated_on
deleted_at
(paranoia
gem)
lock_version
type
id
#{table_name}_count
position
parent_id
lft
rgt
quote_value

Ruby 保留字

alias
and
BEGIN
begin
break
case
class
def
defined?
do
else
elsif
END
end
ensure
false
for
if
module
next
nil
not
or
redo
rescue
retry
return
self
super
then
true
undef
unless
until
when
while
yield
_ FILE _
_ LINE _

【讨论】:

  • 哦,伙计...现在似乎每个字都被占用了!我将不得不使用前缀或后缀来命名我的模型; ScottCubeCube2!
  • 此表中的“Original Rails Wiki”是什么意思?
【解决方案2】:

列名type也被保留,不会出现在MyModel.methods的列表中!

The single-table inheritance mechanism failed to locate the subclass: 'f'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Project.inheritance_column to use another column for that information.

有没有人使用过categoryclasstransactiongroup 等名称?当我在我的数据库中对数据进行分类时,所有这些都会浮现在脑海中......

【讨论】:

    【解决方案3】:

    这是 Rails 5.1.5 的列表:

    !
    !=
    !~
    <=>
    ==
    ===
    =~
    []
    []=
    __binding__
    __callbacks
    __callbacks?
    __id__
    __send__
    _before_commit_callbacks
    _before_commit_without_transaction_enrollment_callbacks
    _commit_callbacks
    _commit_without_transaction_enrollment_callbacks
    _create_callbacks
    _destroy
    _destroy_callbacks
    _find_callbacks
    _initialize_callbacks
    _read_attribute
    _reflections
    _reflections?
    _rollback_callbacks
    _rollback_without_transaction_enrollment_callbacks
    _run_before_commit_callbacks
    _run_before_commit_without_transaction_enrollment_callbacks
    _run_commit_callbacks
    _run_commit_without_transaction_enrollment_callbacks
    _run_create_callbacks
    _run_destroy_callbacks
    _run_find_callbacks
    _run_initialize_callbacks
    _run_rollback_callbacks
    _run_rollback_without_transaction_enrollment_callbacks
    _run_save_callbacks
    _run_touch_callbacks
    _run_update_callbacks
    _run_validate_callbacks
    _run_validation_callbacks
    _save_callbacks
    _touch_callbacks
    _update_callbacks
    _validate_callbacks
    _validation_callbacks
    _validators
    _validators?
    `
    accessed_fields
    acts_like?
    add_to_transaction
    aggregate_reflections
    aggregate_reflections?
    as_json
    assign_attributes
    association
    association_cached?
    attribute_aliases
    attribute_aliases?
    attribute_before_last_save
    attribute_change
    attribute_change_to_be_saved
    attribute_changed?
    attribute_changed_in_place?
    attribute_for_inspect
    attribute_in_database
    attribute_method_matchers
    attribute_method_matchers?
    attribute_missing
    attribute_names
    attribute_present?
    attribute_previously_changed?
    attribute_was
    attributes
    attributes=
    attributes_before_type_cast
    attributes_changed_by_setter
    attributes_in_database
    becomes
    becomes!
    before_committed!
    blank?
    byebug
    cache_key
    cache_timestamp_format
    cache_timestamp_format?
    changed
    changed?
    changed_attribute_names_to_save
    changed_attributes
    changed_for_autosave?
    changes
    changes_applied
    changes_internally_applied
    changes_to_save
    class
    class_eval
    clear_attribute_changes
    clear_changes_information
    clone
    column_for_attribute
    committed!
    connection_handler
    debugger
    decrement
    decrement!
    deep_dup
    default_connection_handler
    default_connection_handler?
    default_scope_override
    default_scopes
    default_timezone
    define_singleton_method
    defined_enums
    defined_enums?
    delete
    destroy
    destroy!
    destroyed?
    destroyed_by_association
    destroyed_by_association=
    display
    dump_schema_after_migration
    dump_schemas
    dup
    duplicable?
    encode_with
    enum_for
    eql?
    equal?
    error_on_ignored_order
    error_on_ignored_order_or_limit
    errors
    extend
    freeze
    from_json
    frozen?
    gem
    has_attribute?
    has_changes_to_save?
    hash
    html_safe?
    id
    id=
    id?
    id_before_type_cast
    id_in_database
    id_was
    in?
    include_root_in_json
    include_root_in_json?
    increment
    increment!
    index_nested_attribute_errors
    init_with
    initialize_internals_callback
    inspect
    instance_eval
    instance_exec
    instance_of?
    instance_values
    instance_variable_defined?
    instance_variable_get
    instance_variable_names
    instance_variable_set
    instance_variables
    invalid?
    is_a?
    itself
    kind_of?
    load_dependency
    lock!
    lock_optimistically
    lock_optimistically?
    locking_enabled?
    logger
    mark_for_destruction
    marked_for_destruction?
    method
    method_missing
    methods
    model_name
    nested_attributes_options
    nested_attributes_options?
    new_record?
    nil?
    no_touching?
    object_id
    partial_writes
    partial_writes?
    persisted?
    pluralize_table_names
    pluralize_table_names?
    populate_with_current_scope_attributes
    presence
    presence_in
    present?
    pretty_inspect
    pretty_print
    pretty_print_cycle
    pretty_print_inspect
    pretty_print_instance_variables
    previous_changes
    primary_key_prefix_type
    private_methods
    protected_methods
    pry
    public_method
    public_methods
    public_send
    query_attribute
    quoted_id
    raw_write_attribute
    read_attribute
    read_attribute_before_type_cast
    read_attribute_for_serialization
    read_attribute_for_validation
    readonly!
    readonly?
    record_timestamps
    record_timestamps=
    record_timestamps?
    reload
    remote_byebug
    remove_instance_variable
    require_dependency
    require_or_load
    respond_to?
    respond_to_without_attributes?
    restore_attributes
    rollback_active_record_state!
    rolledback!
    run_callbacks
    save
    save!
    saved_change_to_attribute
    saved_change_to_attribute?
    saved_changes
    saved_changes?
    schema_format
    send
    serializable_hash
    singleton_class
    singleton_method
    singleton_methods
    skip_time_zone_conversion_for_attributes
    skip_time_zone_conversion_for_attributes?
    slice
    store_full_sti_class
    store_full_sti_class?
    suppress_warnings
    table_name_prefix
    table_name_prefix?
    table_name_suffix
    table_name_suffix?
    taint
    tainted?
    tap
    time_zone_aware_attributes
    time_zone_aware_types
    time_zone_aware_types?
    timestamped_migrations
    to_enum
    to_gid
    to_gid_param
    to_global_id
    to_json
    to_key
    to_model
    to_param
    to_partial_path
    to_query
    to_s
    to_sgid
    to_sgid_param
    to_signed_global_id
    to_yaml
    toggle
    toggle!
    touch
    touch_later
    transaction
    trust
    try
    try!
    type_for_attribute
    unloadable
    untaint
    untrust
    untrusted?
    update
    update!
    update_attribute
    update_attributes
    update_attributes!
    update_column
    update_columns
    valid?
    validate
    validate!
    validates_absence_of
    validates_acceptance_of
    validates_confirmation_of
    validates_exclusion_of
    validates_format_of
    validates_inclusion_of
    validates_length_of
    validates_numericality_of
    validates_presence_of
    validates_size_of
    validates_with
    validation_context
    warn_on_records_fetched_greater_than
    will_save_change_to_attribute?
    with_lock
    with_options
    with_transaction_returning_status
    write_attribute
    yield_self
    

    你可以得到它

    ActiveRecord::Base.instance_methods.sort
    

    【讨论】:

      【解决方案4】:

      打开一个 Rails 控制台和一个类型 MyModel.methods

      所有列出的方法都是保留字。

      【讨论】:

      • 这可能会导致误报。现有的方法和列名会显示出来,让人认为他们一直在使用保留字。
      • @gg_s 如果您有另一个没有可疑列的模型,这很容易处理
      • 试试ActiveRecord::Base.instance_methods
      • 对于按字母顺序排序的列表,请在 Rails 控制台中执行以下操作:pp ActiveRecord::Base.instance_methods.sort; nil
      • 这并没有提供完整的列表,大部分只是您不应该用于方法名称的名称,而不是您的模型名称。
      猜你喜欢
      • 2013-07-11
      • 2012-09-07
      • 2012-07-20
      • 2015-05-25
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-26
      • 2010-12-26
      相关资源
      最近更新 更多