0

我正在尝试在 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

有任何想法吗?

4

3 回答 3

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 值部分)

于 2013-10-25T13:32:22.067 回答
3

我想你想要的是这个

User.columns_hash.each do |key, value|
 key
 value.type
end

value.type会给你类型作为符号。如果您希望将其转换为字符串,则可以将其转换为字符串

于 2013-10-25T13:34:36.080 回答
1

知道了!需要像这样使用 columns_hash :

Event.columns_hash.each {|k,v| puts "#{k} => #{v.type}"}

归功于获取 ActiveRecord 对象中的属性类型

于 2013-10-25T13:46:55.483 回答