Naresh Kumar.P Naresh Kumar.P - 1 year ago 46
Ruby Question

Get the value of Json Array in View from Controller Rails 4

I need to get the value of the Json Array in the View Page that i have assigned in Rails 4.

My Controller: Profile_controller.rb

class ProfileController < ApplicationController
before_filter :authenticate_user!
def initialize

def search_view
@user_t_table=User.where.not(gender: @user_gender)
@user_t_table.each do |user|
sql = "SELECT, users.first_name FROM users LEFT JOIN user_profiles ON = user_profiles.user_id LEFT JOIN educations ON = educations.user_id LEFT JOIN usercontacts ON = usercontacts.user_id WHERE user_profiles.height >='1' AND user_profiles.height <='3' AND user_profiles.marital_status='1' AND user_profiles.mother_tongue='1' AND usercontacts.country_id='1' AND usercontacts.state_id='1' AND usercontacts.city_id='1' AND educations.highest_education='1' AND users.religion_id='1' AND users.caste_id='1' AND ='#{}'"
records_array = ActiveRecord::Base.connection.execute(sql)
@search_value << records_array

I need @search_value to be printed in the View page and here is my json Output that i get when i put render to the Value.

Json Output is:


My view Page is search_view.html.erb

<% @search_value.each_with_index do |group,index| %>
<!-- Render stuff -->
<%#<%= group %>
<% group.each_with_index do |child,indexs| %>
<!-- Render child stuff -->
<%= child %>
<% end %>
<% end %>

I need to get the id from the json Output. Pls help to get it.

Answer Source

Try: Array#flatten

 > search_result = [[{"id":1,"first_name":"sharma","0":1,"1":"sharma"}],[]]
 > search_result.flatten
 #=> [{:id=>1, :first_name=>"sharma", :"0"=>1, :"1"=>"sharma"}]

In your view file search_view.html.erb:

<% @search_value.flatten.each_with_index do |group,index| %>
  <%= group["id"] %>      
  <%= group["first_name"] %>
<% end %>

Note: Your @search_value's JSON output is not seems like json. json looks like "[[{\"id\":1,\"first_name\":\"sharma\",\"0\":1,\"1\":\"sharma\"}],[]]" anyway you can parse your json using JSON.parse