我正在尝试在rails中构建一个生成器但是我在尝试访问现有模型的参数时遇到困难。基本上我想做这样的事情:
# user is a model the has the parameters "id: integer, name: string, and email: string"
User.parameters.each do |parameter|
# do something with id, name, email
parameter.key
# do something with integer, string, string
parameter.value
end
有什么想法吗?
答案 0 :(得分:3)
我认为你正在寻找属性,而不是参数。
user = User.first
user.attributes.each do |key, value|
# do something here with keys and values
puts key if key
puts value if value
end
注意我正在抓取模型的实际实例以及检查nils(if键/ if值部分)
答案 1 :(得分:3)
我认为你想要的是这个
User.columns_hash.each do |key, value|
key
value.type
end
value.type
会为您提供类型作为符号。如果您希望将其转换为字符串
答案 2 :(得分:1)
知道了!需要像这样使用columns_hash:
Event.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}
归功于Getting types of the attributes in an ActiveRecord object