SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2006
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    ActiveRecord question

    Hi guys.

    Im completely new to rails and have trying to get my head around activerecord.

    I have these ruby objects

    Code:
    class Client < ActiveRecord::Base
    belongs_to :client_organisation
    
    end
    
    class ClientOrganisation < ActiveRecord::Base
    has_many :client
    end
    With a mysql database to reflects this.

    what im trying to do is
    Code:
    @client = Client.find(params[:id])
    @client.client_organisation  #this returns nil
    @client.client_organisation_id #this returns the right foreign key id

    Now from my understand @client.client_organisation should return a ClientOrganisation object. Is there a method to make the @client load its relational objects? Is there anything else I am missing, off track on?

    Thanks you the help

    Alistair

  2. #2
    SitePoint Evangelist
    Join Date
    Jun 2004
    Location
    California
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not sure why, it should autoload that, but you could add this to the find:
    Code:
    @client = Client.find(params[:id], :include => :client_organisation)
    Happy switcher to OS X running on a MacBook Pro.

    Zend Certified Engineer

  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)
    It should definately be loading it automatically - adding the include statement just tells Rails to load the associated objects with one query using JOINS for a speed increase.

    I can't see any immediate problem with your code, can you post your schema?

  4. #4
    SitePoint Enthusiast
    Join Date
    Feb 2006
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your help.

    What I had wrong was the foreign key was client_organisations_id when it should have been client_organisation_id. Looking at the example I gave I got it right there but not in my live code.


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
  •