在Rails中显示嵌套哈希的结果

时间:2015-06-04 02:32:41

标签: ruby-on-rails ruby ruby-on-rails-4 linkedin omniauth

我已成功将LinkedIn API实施到我的rails应用程序中。

API返回位置字段中的数据,其中包含来自最后2个位置的详细信息的更多字段。它包括标题,持续时间,描述等......

如何在我的rails应用程序中将此分解为获取第二个作业的职称的字段数据?

例如,我希望链接到user.positions.title.1的第二个位置的标题

auth.extra.raw_info.positions.values在数据库中包含以下内容

[2, [#<OmniAuth::AuthHash company=#<OmniAuth::AuthHash id=165676 industry="Marketing and Advertising" name="ReachLocal" size="1001-5000 employees" ticker="RLOC" type="Public Company"> id=666166336 isCurrent=true startDate=#<OmniAuth::AuthHash month=2 year=2015> title="UX/UI Designer">, #<OmniAuth::AuthHash company=#<OmniAuth::AuthHash id=1246381 industry="Media Production" name="Freelance" size="Myself Only" type="Self-Employed"> id=561193709 isCurrent=true startDate=#<OmniAuth::AuthHash month=6 year=2014> summary="- Defining business requirements by determining the success metrics, identifying the target demographic, and understanding the project objective/goals \n\n - Conducting evidence-based user research through interviews and usability testing before and after the redesign\n\n - Delivering detailed information architecture, interaction and visual design specifications to stakeholders\n\n - Developing mental models through UX best practices\n\n - Creating actionable and intuitive design flows\n\n - Designing, building, and testing interactive prototypes to iterate and evolve design concepts of the project" title="UX Designer">]]

模型

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.headline = auth.info.headline
    user.first_name = auth.info.first_name
    user.last_name = auth.info.last_name
    user.industry = auth.info.industry
    user.location = auth.info.location
    user.summary = auth.extra.raw_info.summary
    user.connections = auth.extra.raw_info.numConnections
    user.linkedin_photo_url = auth.info.image
    user.linkedin_url = auth.info.urls.public_profile
    user.linkedin_position = auth.extra.raw_info.positions.values
  end

1 个答案:

答案 0 :(得分:0)

因此,您的Array长度为2。要获取第二个元素,您可以使用[1];和.title标题。

即:auth.extra.raw_info.positions.values[1].title

注意:索引从零开始;即[0]是第一个元素,[1]是第二个元素,等等。