SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast Stevenwulf's Avatar
    Join Date
    May 2002
    Location
    Berkeley
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Adding custom Attributes to ActiveRecord

    Subject line states the question. I'm adding the following to an
    ActiveRecord class:

    Code:
     class Institution < ActiveRecord::Base
     
       # list of associations
       has_and_belongs_to_many(:license_types)
     
       attr_accessor :tmp_license_types
     
       public
       def initialize(attributes = nil)
         super(attributes)
         @tmp_license_types = Array.new
         self.license_types.each { |lt| self.tmp_license_types << lt }
     end
    The problem is that if I try to access this attribute in my controller I
    keep getting a nil object error. Also, I tried calling

    Code:
     <%= debug(@institution) %>
    in my view an this extra attribute that I added is not being reported.
    Any ideas?

    Thanks,
    Steven

  2. #2
    SitePoint Addict SRTech's Avatar
    Join Date
    Mar 2005
    Posts
    224
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    First of all, I think you are missing and 'end' after the 'def' unless this is not all the code in the file.

    Second, try getting rid of the 'public' section. I don't know if it wil solve the issue, but I don't think you need it. (but I could be wrong)

  3. #3
    SitePoint Guru silver trophy Luke Redpath's Avatar
    Join Date
    Mar 2003
    Location
    London
    Posts
    794
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You are making a mistake I recently made, and that is to use the initialize() function - this can cause problems with ActiveRecord.

    You should instead define

    Code:
    def after_initialize
     # stuff
    end
    Instead. That might fix your problem.

  4. #4
    SitePoint Enthusiast Stevenwulf's Avatar
    Join Date
    May 2002
    Location
    Berkeley
    Posts
    76
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


    Exactly what I needed. Thanks Luke!

    -Steven


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •