【发布时间】:2018-04-09 05:31:11
【问题描述】:
假设我的一个名为 Company 的模型中有以下哈希。
FIELDS = {
TEAM: {
'num_founders': 'Number of Founders',
'num_employees': 'Number of Employees',
'founders': {
'person_info': {
'full_name': 'Full Name',
'first_name': 'First Name',
'last_name': 'Last Name',
'location': 'Location',
'gender': 'Gender',
'biography': 'Biography',
'num_articles': 'Number of Articles'
}
}
}
}
我的应用程序控制器中有一个操作,它将这个哈希呈现为 json:
def field_names
module_name = params[:module]
category = params[:category]
case module_name
when 'company'
render json: Company::FIELDS[category.to_sym].to_json
end
end
所以现在如果我打开 localhost:3000/field_names/company/TEAM 我会得到 json。但是我现在面临的问题是我也需要获取这个散列的子散列。就像我想/field_names/company/TEAM/founders/person_info 并获取相应的对象。
首先,我会用斜杠分割网址以获取密钥。我无法弄清楚如何使用这些字符串来访问哈希。
如果我像get '/field_names/:query', to: 'application#field_names这样定义路由
如果我点击localhost:3000/field_names/company/TEAM/founders
该操作应呈现 Company::FIELDS[:TEAM]["founders"] 对象,这将是
'person_info': {
'full_name': 'Full Name',
'first_name': 'First Name',
'last_name': 'Last Name',
'location': 'Location',
'gender': 'Gender',
'biography': 'Biography',
'num_articles': 'Number of Articles'
}
为此,我的操作应该是:
def field_names
query = params[:query]
keys = query.split("/")
#keys.first::FIELDS[key2][key3]... .to_json
end
我如何实现这一目标?谢谢:)
【问题讨论】:
标签: ruby-on-rails json ruby hash