Get specific attributes from an ActiveRecord model

后端 未结 4 1733
你的背包
你的背包 2021-01-30 10:43

Let\'s say that I have a User model with attributes :id, :first_name, :last_name, and :email. In my application, guest users shouldn\'t see User\

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 11:07

    Had a requirement like this but wanted something more generic that would just gather a list of method names and values from a model (including attributes). So, I added this method to my model:

      def attributes_from_keys(*keys)
        keys.inject({}) do |hash_to_return, key|
          hash_to_return.merge(key => send(key))
        end
      end
    

    Then, call this method with:

    MyModel.find(1).attributes_from_keys(:id, :name, :age)
    

    returns

    {id: 1, name: 'Lawrence', age: 23}
    

提交回复
热议问题