简体   繁体   English

如何在可枚举的 object 中用 Ruby/Rails 中的“None”替换 nil 和“空字符串”?

[英]How to replace nil and 'empty string' with “None” in Ruby/Rails in enumerable object?

I'm taking to objects in Rails: a Record::ActiveRecord_Relation and a ActionController::Parameters and turn them into usable Hashes to be rendered in Views.我正在使用 Rails 中的对象:Record::ActiveRecord_Relation 和 ActionController::Parameters 并将它们转换为可用的哈希值,以便在视图中呈现。 I need to replace nil and "" with "none".我需要将 nil 和 "" 替换为 "none"。 I could do it the non-dry way and protect every key/value pair of the Hash with something like:我可以用非干的方式来保护 Hash 的每个键/值对,例如:

  <div><%= @records_incoming[:time_inserted] || @records_incoming[:time_inserted].empty? ? "none" : @records_incoming[:time_inserted]  %></div>

but that doesn't seem very Ruby like (granted, I'm a newer developer).但这似乎不太像 Ruby (当然,我是新开发人员)。

I've tried to handle this in the controller like so:我试图在 controller 中处理这个问题,如下所示:


def show
    sent_results = Record.get_sent(params[:request][:trans_uuid]) 

    if !sent_results.empty? 

      incoming_request = params[:request].permit!
      @records_sent = sent_results[0].attributes.each { |k,v| v.class == String && v.empty? || !v ? sent_results[0].attributes[k] = "none" : sent_results[0].attributes[k] } 
      @records_incoming = incoming_request.to_h.map { |k, v| v.empty? || !v ? "none" : v }
      byebug 
    else    
      flash[:error] = 'No record found'
    end 
  end

but this does not change the nil and empty string values to 'none'.但这不会将 nil 和空字符串值更改为“无”。 If I use map , I of course get an array as the return value but I need to retain a Hash.如果我使用map ,我当然会得到一个数组作为返回值,但我需要保留一个 Hash。

Please advise on any better Rails ways to do this overall.请就总体上更好的 Rails 方法提出建议。 Trying to get 2 hashes into views to be split out and rendered.试图将 2 个哈希值放入要拆分和渲染的视图中。

You can try using presence .您可以尝试使用presence

<%= @records_incoming[:time_inserted].presence || "none" %>

It handles the two cases you need, @records_incoming[:time_inserted] being nil or an empty string as it returns the receiver if it's present?它处理您需要的两种情况, @records_incoming[:time_inserted]为 nil 或空字符串,因为它返回接收器(如果present? . .

You can use transform_values!您可以使用transform_values! on params hash在参数 hash

try,尝试,

incoming_request.transform_values! { |v| v.empty? || !v ? "none" : v }
@records_incoming = incoming_request

Ref: transform_values!参考: transform_values! doc文档

Note: transform_values!注意: transform_values! updates the hash in place更新 hash 到位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM