开发者

rails 3 - if form field blank make value this instead

I hav开发者_JAVA百科e a model called Post in my Rails 3 app.

Users can create their own urls for these posts. (I call this a clean_url.)

If the user does not complete this field, I want to create the value myself from the title upon saving the form. (Essentially use the @post.title.to_s(some reg ex to remove spaces etc...)

What is the best approach to having the item save with title value in this field if it is left blank?

I assumed in the Posts controller create action I could "update_attributes" of the post upon saving... but Im beginning to think maybe this is wrong?

Anyone have ideas on how to achieve this?


Use a before_save callback, and a private method in your model. The following is taken straight from my blog source.

before_save :create_clean_url

private

def create_clean_url
  if self.clean_url.blank?
    # Remove non-alpha characters. Replace spaces with hyphens.
    self.clean_url = self.title.downcase.gsub(/[^(a-z0-9)^\s]/, '').gsub(/\s/, '-')
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜