0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】modelに設定しているattr_accessorの全ての値を取得したかった

Posted at

使えるかどうかは、個々人のプロジェクト・プログラムに委ねるとして、今回は個人用メモとして、雑にコードを載せておくだけです。

内容

各モデルで設定されているattr_accessorの値全てを取得する。

コード

model
class ApplicationRecord < ActiveRecord::Base
  def accessor_attributes
    accessor_attributes = {}
    self.class.attr_accessors.each do |accessor|
      accessor_attributes[accessor] = public_send(accessor)
    end
    accessor_attributes
  end

  class << self
    def attr_accessor(*vars)
      @attr_accessors = vars
      super
    end

    attr_reader :attr_accessors
  end
end

class User < ApplicationRecord
  # DBには保存しない何かしらの値を格納する変数
  attr_accessor :type, :name
end

attr_accessorに設定している全ての値を取得する

controllerなど
user = User.last
user.type = 'admin' 
user.name = 'Hello Qiita'

# attr_accessorに指定してある値を取得
user.accessor_attributes
# => { type: 'admin', name: 'Hello Qiita' }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?