Skip to content

Instantly share code, notes, and snippets.

@8parth
Last active March 29, 2017 17:07
Show Gist options
  • Save 8parth/e16acd0a927a265f00ebbfb41edd9628 to your computer and use it in GitHub Desktop.
Save 8parth/e16acd0a927a265f00ebbfb41edd9628 to your computer and use it in GitHub Desktop.
Rails 5 Attributes API
class User < ApplicationRecord
# rails 4 way of defining virtual attribute
attr_accessor :full_name
# new rails 5 way of defining virtual attributes with datatype and default values
attribute :name, :string, default: -> { "No Name" }
attribute :age, :float, default: 99
before_save :assign_name
before_save :assign_full_name
def assign_name
self.name = "#{first_name} #{last_name}"
end
def assign_full_name
self.full_name = "#{first_name} #{last_name}"
end
end
In rails console:
irb:> User.new
=> #<User id: nil, first_name: nil, last_name: nil, age: "99", created_at: nil, updated_at: nil, name: "No Name">
irb:> u = User.new(first_name: "Harry", last_name: "Potter")
irb:> u.save
irb:> u
=> #<User id: 1, first_name: "Harry", last_name: "Potter", age: 99.0, created_at: "2017-03-29 16:30:16", updated_at: "2017-03-29 16:30:16", name: "Harry Potter">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment