Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Update a Rails readonly field
2.1.5 :020 > User
=> User(id: integer, name: string, email: string, created_at: datetime, updated_at: datetime)
2.1.5 :021 > User.create(name: 'rob', email: 'orb@example.com')
(0.1ms) begin transaction
SQL (1.0ms) INSERT INTO "users" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "rob"], ["email", "orb@example.com"], ["created_at", "2015-01-09 08:50:31.962223"], ["updated_at", "2015-01-09 08:50:31.962223"]]
(0.8ms) commit transaction
=> #<User id: 2, name: "rob", email: "orb@example.com", created_at: "2015-01-09 08:50:31", updated_at: "2015-01-09 08:50:31">
2.1.5 :022 > User.first
User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 2, name: "rob", email: "orb@example.com", created_at: "2015-01-09 08:50:31", updated_at: "2015-01-09 08:50:31">
2.1.5 :023 >
2.1.5 :024 > User.first.update(email: 'rob@example.com')
User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
SQL (1.4ms) UPDATE "users" SET "updated_at" = ? WHERE "users"."id" = ? [["updated_at", "2015-01-09 08:51:20.188838"], ["id", 2]]
(1.0ms) commit transaction
=> true
2.1.5 :025 > User.first
User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 2, name: "rob", email: "orb@example.com", created_at: "2015-01-09 08:50:31", updated_at: "2015-01-09 08:51:20">
2.1.5 :026 > User.class_eval do
2.1.5 :027 > def self.readonly_attributes
2.1.5 :028?> []
2.1.5 :029?> end
2.1.5 :030?> end
=> :readonly_attributes
2.1.5 :031 >
2.1.5 :032 > User.first.update(email: 'rob@example.com')
User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
SQL (0.4ms) UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["email", "rob@example.com"], ["updated_at", "2015-01-09 08:53:32.479937"], ["id", 2]]
(2.8ms) commit transaction
=> true
2.1.5 :033 > User.first
User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 2, name: "rob", email: "rob@example.com", created_at: "2015-01-09 08:50:31", updated_at: "2015-01-09 08:53:32">
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string
# email :string
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
attr_readonly :email
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment