简体   繁体   中英

Attaching conditional methods(or attributes?) to a rails model

I'm using the friendly_id plugin to generate SEO-friendly URLS for some of my models.

Currently, I have a model with two attributes: name and display_name.

Essentially, display_name is preferred, but if it is blank, the model reverts to name. Friendly_id needs a field to base the URL off of:

Class Market < ActiveRecord::Base
  has_friendly_id :name
end

How can I implement something that looks (logically) like this:

Class Market < ActiveRecord::Base
  if self.display_name
    has_friendly_id :display_name
  else
    has_friendly_id :name
  end
end

Thanks!

Maybe something like this?

Class Market < ActiveRecord::Base
  has_friendly_id :friendly_name

  def friendly_name
    self.display_name || self.name
  end
end

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