Topic: Rails model custom setter/getter methods FAIL

what am I doing wrong here?

I have a model for an app I am writing called page. Those attributes are:
title
pagetype
page_url

title and pagetype can be set as normally, but I used a custom getter/setter for the page_url. Here is the logic/model:

class Page < ActiveRecord::Base

   def page_url=()
        temp = self[:title]
        pageUrl = temp.gsub(" ", "_").downcase  
  if self[:pagetype] == "home"
          pageUrl = "/"
        end
        self[:page_url] = pageUrl
    end
    
    def page_url
        self[:page_url]
    end

end

It's fairly simple -> page_url is based on the title with all spaces replaced with unless page_type == "home", which then gets set to "/". For the record I don't want to make page_url virtual because I need it to be searchable and saved in the d.

So unfortunately whether in rails console or my app this is failing. Here is how I am calling the setter method in the console;

page1 = Page.new
page1.pagetype = "home"
page1.title = "this is a test"

page2 = Page.new
pager2.pagetype = "content"
page2.title = "this is another test"

#expected results should be
page1.page_url() 
=> "/"
page2.page_url()
=> "this_is_another_test"

However I keep getting this:

page1.page_url()
=> nil

What the heck am I doing wrong here?

Re: Rails model custom setter/getter methods FAIL

I got a response from stackexchange - http://stackoverflow.com/questions/1063 … od-failing

These custom setter and getters don't persist to the database. If you have a column page_url in your database, you can set the value with a callback. E.g. before_save:

class Page < ActiveRecord::Base
  before_save :set_page_url

  def set_page_url
    if self[:pagetype] == "home"
      self.page_url = "/"
    else
      self.page_url = self[:title].gsub(" ", "_").downcase
    end
  end
end