在我的代码中,我正在解析像JSON这样的对象
[{"name":"karthi"},{"name":"shreshtt"},{"name":"jitu"},{"name":null},{"name":null},{"name":null},{"name":null}]
在此,我想收集单个数组对象中的所有名称。这就是我的控制器现在的样子。我想将结果名称数组存储在@hotels
变量中。
controller.erb
respond_to :json, :xml
def index
@hotels = Hotel.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: @hotels.to_json(:only => [ :name ]) }
end
end
查看/旅馆住宿/ index.json.erb
[
hotel: <% @hotels.each do |hotel| %>
{ 'name': "<%= hotel.name.to_json.html_safe %>" }
<% unless index== @hotels.count - 1%>
<% end %>
<% end %>
]
答案 0 :(得分:0)
您想只将名称添加到数组中吗? 怎么样:
a = [{name: "karthi"},{name: "shreshtt"},{name: "jitu"},{name: nil},{name: nil},{name: nil},{name: nil}]
@hotel = []
a.collect{|a_name| @hotel << a_name[:name]}
=> ["karthi", "shreshtt", "jitu", nil, nil, nil, nil]
@hotel.compact!
=> ["karthi", "shreshtt", "jitu"]
答案 1 :(得分:0)
那是什么意思?
a = {}
a["hotel"] = []
array = [{"name"=>"kathi"}, {"name"=>"kathi2"}, {"name"=>"kathi3"}, {"name"=>"kathi4"}, {"name" => nil}]
a["hotel"] = array
a["hotel"].each do |v|
if v["name"] == nil
a["hotel"].delete(v)
end
end
a => {"hotel"=>[{:name=>"kathi"}, {:name=>"kathi2"}, {:name=>"kathi3"}, {:name=>"kathi4"}]}
答案 2 :(得分:0)
您可以执行以下操作
hotels = Hotel.select("name").where("name is not NULL")
json_obj = {hotels: hotels}.to_json
format.json { render json: json_obj }