POSTS
Rails从对象或者hash中获取、去除某些属性
1.在ActiveRecord中获取指定属性值,slice会获取指定属性后再转换成hash
通常的做法
class Permission < ApplicationRecord
has_and_belongs_to_many :role_tpls
def to_json
{
resource: self.resource,
status: self.status,
name: self.name,
allow: self.allow
}
end
end
使用slice方法:
class Permission < ApplicationRecord
has_and_belongs_to_many :role_tpls
def to_json
self.slice(:resource, :status, :name, :allow)
end
end
这个方法不是rails特有的,ruby中也能用:
➜ irb
2.6.2 :001 > a = {name: 'dx', age: 18, gender: 1}
=> {:name=>"dx", :age=>18, :gender=>1}
2.6.2 :002 > a.slice(:name, :age)
=> {:name=>"dx", :age=>18}
2.使用except排除某些属性
#先使用attributes方法转换从hash,再使用except方法去除password_digest属性
@users = User.all.map {|user| user.attributes.except("password_digest")}
#但只能在rails中使用,ruby中的hash并没有此方法
➜ irb
2.6.2 :001 > a = {name: 'dx', age: 18, gender: 1}
=> {:name=>"dx", :age=>18, :gender=>1}
2.6.2 :003 > a.except(:gender)
NoMethodError (undefined method `except' for {:name=>"dx", :age=>18, :gender=>1}:Hash)