Topic: derived columns/attributes

Hi!
I have a model named link, which contains the columns name (for building the url, e.g. this_is_a_link) and description (which is shown to the user, e.g. This is a link).
Now i have two questions:
1. A Link should be created like this: Link.create(:name => 'This is a link'). Internally, the model should set description=name.downcase.strip.gsub(' ', '_'), where can i realize this? I tried the initialize-method of class link, but i didn't succeed.
2. A link should have the method url() (http://mywebsite.de/whatever/this_is_a_link), which should use a named route or url_for method. But these methods i can only use in controller and helper methods, so must i place such a method there?
Thanks at all and excuse for my bad english wink.
Kai

Re: derived columns/attributes

gayson wrote:

1. A Link should be created like this: Link.create(:name => 'This is a link'). Internally, the model should set description=name.downcase.strip.gsub(' ', '_'), where can i realize this? I tried the initialize-method of class link, but i didn't succeed.

Try this:

class Link < ActiveRecord::Base
  before_create :generate_description
 
  def generate_description
    self.description = name.downcase.strip.gsub(' ', '_')
  end
end

gayson wrote:

2. A link should have the method url() (http://mywebsite.de/whatever/this_is_a_link), which should use a named route or url_for method. But these methods i can only use in controller and helper methods, so must i place such a method there?

If you need access to named routes you'll need to put this in the controller or view. I recommend creating a helper method called "url_for_link(link)" which will generate the URL.

Railscasts - Free Ruby on Rails Screencasts

Re: derived columns/attributes

That was it!
Thank you for both perfect answers!
I just want to be sure, that the description updated on update of name, have i just to add

before_update :generate_description

?

Last edited by gayson (2007-02-28 18:21:06)

Re: derived columns/attributes

You could do that, or just use "before_save" which will take place for both update and create.

Railscasts - Free Ruby on Rails Screencasts