简体   繁体   中英

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

I have the following model defined (Using Mongoid, not active record)

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:

<%= 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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