Концепция называется "десериализация", поэтому я сделал для этого свой собственный драгоценный камень: quickery
.
Использование quickery
class Event < ApplicationRecord
belongs_to: user
quickery { user: { username: :host } }
end
Использование Normal-Way
class Event < ApplicationRecord
belongs_to :user
before_save do
host = user.username
end
end
class User < ApplicationRecord
has_many :events
# you may want to comment out this `after_destroy`, if you don't want to cascade when deleted
after_destroy do
events.update_all(host: nil)
end
# you may want to comment out this `after_update`, if you don't want each `event.host` to be updated (automatically) whenever this `user.username` gets updated
after_update do
events.update_all(host: username)
end
end
Пример использования (для любого из вышеперечисленных)
user = User.create!(username: 'foobar')
event = Event.create!(user: user)
puts event.host
# => 'foobar'