How to retrieve the hash values in the views in rails

丶灬走出姿态 提交于 2019-12-24 10:58:17

问题


I have an action in the controller:

def user_detail
    @user_detail = UserDetail.find_by_id(11)
end

And in the view:

<%= @user_detail -%> // displays me like #

I am trying to retrieve the contents of @user_detail: actually the hash contains {:empid=>"11111", :prjtname=>"aaaaa", :prjtrole=>"Developer"}

How do I display the user detail's empid and other values?


回答1:


Since I know what question you asked earlier, I think this is the syntax you actually want to use:

<%= @user_detail.additional_info[:empid] %>

Unless of course you renamed the name of the hash :)

Another approach, if you want all the content from the hash but the keys varies from each record, you could loop through them like this:

<% @user_detail.additional_info.each_pair do |key, value| %>
  <p>Key: <%= key %> Value: <%= value %></p>
<% end %>



回答2:


To get simple debug output like the example you posted, this will handle it:

<%= @user_detail.inspect %>



回答3:


try this <%= @user_detail.emplid %> <%= @user_detail.prjtname %> <%= @user_detail.prjtr %>




回答4:


More of an extraction from @dln's answer

try using

<%= @user_detail[:emplid] %>
<%= @user_detail[:prjtname] %>
<%= @user_detail[:prjtr] %>

Hope this solves your prob



来源:https://stackoverflow.com/questions/4395466/how-to-retrieve-the-hash-values-in-the-views-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!