提交 8587cf0d 编写于 作者: S Sean Griffin

Merge pull request #21720 from byroot/ignore-columns

Implement ActiveRecord::Base.ignored_columns
......@@ -32,6 +32,11 @@
*Yves Senn*, *Matthew Draper*
* Add `ActiveRecord::Base.ignored_columns` to make some columns
invisible from ActiveRecord.
*Jean Boussier*
* `ActiveRecord::Tasks::MySQLDatabaseTasks` fails if shellout to
mysql commands (like `mysqldump`) is not successful.
......
......@@ -50,6 +50,13 @@ module ModelSchema
class_attribute :pluralize_table_names, instance_writer: false
self.pluralize_table_names = true
##
# :singleton-method:
# Accessor for the list of columns names the model should ignore. Ignored columns won't have attribute
# accessors defined, and won't be referenced in SQL queries.
class_attribute :ignored_columns, instance_accessor: false
self.ignored_columns = [].freeze
self.inheritance_column = 'type'
delegate :type_for_attribute, to: :class
......@@ -308,7 +315,7 @@ def load_schema
end
def load_schema!
@columns_hash = connection.schema_cache.columns_hash(table_name)
@columns_hash = connection.schema_cache.columns_hash(table_name).except(*ignored_columns)
@columns_hash.each do |name, column|
warn_if_deprecated_type(column)
define_attribute(
......
......@@ -1571,4 +1571,22 @@ def test_default_values_are_deeply_dupped
assert_not topic.id_changed?
end
test "ignored columns are not present in columns_hash" do
cache_columns = Developer.connection.schema_cache.columns_hash(Developer.table_name)
assert_includes cache_columns.keys, 'first_name'
refute_includes Developer.columns_hash.keys, 'first_name'
end
test "ignored columns have no attirbute methods" do
refute Developer.new.respond_to?(:first_name)
refute Developer.new.respond_to?(:first_name=)
refute Developer.new.respond_to?(:first_name?)
end
test "ignored columns don't prevent explicit declaration of attribute methods" do
assert Developer.new.respond_to?(:last_name)
assert Developer.new.respond_to?(:last_name=)
assert Developer.new.respond_to?(:last_name?)
end
end
......@@ -7,6 +7,8 @@ def find_least_recent
end
class Developer < ActiveRecord::Base
self.ignored_columns = %w(first_name last_name)
has_and_belongs_to_many :projects do
def find_most_recent
order("id DESC").first
......@@ -61,6 +63,9 @@ def find_least_recent
developer.audit_logs.build :message => "Computer created"
end
attr_accessor :last_name
define_attribute_method 'last_name'
def log=(message)
audit_logs.build :message => message
end
......
......@@ -250,6 +250,7 @@ def except(adapter_names_to_exclude)
create_table :developers, force: true do |t|
t.string :name
t.string :first_name
t.integer :salary, default: 70000
if subsecond_precision_supported?
t.datetime :created_at, precision: 6
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册