简体   繁体   English

Ruby on Rails模型自定义to_s方法,排除nill或空值

[英]Ruby on Rails model custom to_s method, exclude nill or blank values

I have the following model defined (Using Mongoid, not active record) 我定义了以下模型(使用Mongoid,不是活动记录)

class Address
  include Mongoid::Document

  field :extra, type: String
  field :street, type: String
  field :area, type: String
  field :city, type: String
  field :code, type: Integer

  validates :street, :city, presence: true

  def to_s
    "#{extra},#{street},#{area},#{city},#{code}"
  end
end

I am defining the to_s method, so i can just use: 我正在定义to_s方法,所以我可以使用:

<%= address %> 

in my views, and it will print out the address correctly. 在我的视图中,它将正确打印出地址。 However the issue with the code above, if any of the attributes are blank or nil i end up with the following: 但是上面代码的问题,如果任何属性为空或者为零,我最终会得到以下结果:

1.9.3p327 :015 > a
 => #<Address _id: 50f2da2c8bffa6e877000002, _type: nil, extra: "hello", street: nil, area: nil, city: nil, code: nil> 
1.9.3p327 :016 > puts a
hello,,,,,
 => nil 

Using a bunch of unless statements to check if the value is blank or nil seems like the wrong way to go (i can get it to work like that, but seems hackish) 使用一堆除非语句来检查值是空白还是零似乎是错误的方法(我可以让它像这样工作,但似乎是hackish)

What would be a better way of doing this? 这会是一个更好的方法吗?

You can use this 你可以用它

def to_s
  [extra, street, area, city, code].select{|f| !f.blank?}.join(',')
end

Store elements in an array, throw invalid values out, join with separator. 将元素存储在数组中,抛出无效值,与分隔符连接。

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

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