views:

86

answers:

3

A user submits a url, this is put into into article.url through the scaffold create method. I can parse the url like so:

def parse_url
  elements = @article.url.split("/")
  if(elements[0] == "http:")
    @home = elements[2] #elements[1] will be an empty string because of the // in the URL
  else
    @home = elements[0]
  end
end

What I would prefer to do is to parse the url after the user saves it with the create method and then insert this value into a new row in the database in the article table.

A: 

look at the activerecord callbacks, specifically after_save

Omar Qureshi
A: 

class Article < ActiveRecord::Base after_create :clean_url

def clean_url elements = self.article.url.split("/") if(elements[0] == "http:") home = elements[2] #elements[1] will be an empty string because of the // in the URL else home = elements[0] end end So how can I then save this to article.home_page?

+2  A: 

I'd use something like the following:

class Article
  attr_accessor :unparsed_url

  before_validation_on_save :parse_url

  private

  def parse_url
    return unless unparsed_url

    elements = unparsed_url.split("/")
    if(elements[0] == "http:")
      self.home = elements[2]
    else
      self.home = elements[0]
    end
  end
end

You'd use unparsed_url in the Rails forms. Using a virtual attribute like this will work nicely with form validation.

peterjm