#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2001
    Location
    Burlington, VT
    Posts
    344
    Rep Power
    14

    Newbie Modeling/Association Question


    Hello --

    Be forewarned I am new to RoR, but have spent several days trying to figure this out.

    My problem is that I have a database schema where I have a User table & a Task table. The Task table has an assigned_to field and an assigned_by that relates back to the User table.

    I figured that the model would be something like

    class User< ActiveRecord::Base
    has_many :tasks, :foreign_key=>"assigned_by"
    has_many :tasks, :foreign_key =>"assigned_to"
    end

    class Task< ActiveRecord::Base
    belongs_to :user
    end

    I am sure I making a glaring mistake, but just thought I would ask for some help.

    thanks in advance.
    ------------------------------------------------------------
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2005
    Posts
    112
    Rep Power
    10
    Hi,

    First, it would be good if you name your tables as users and tasks (as per the rails convention).

    Now coming back to your problem, you could try the following code instead:

    Code:
    class User< ActiveRecord::Base
      has_many :tasks, :class_name => "Task", :foreign_key=>"assigned_by"
      has_many :todo, :class_name => "Task", :foreign_key =>"assigned_to"
    end
    
    class Task< ActiveRecord::Base
      belongs_to :user
    end
    This way, you can then use user.tasks to see all the tasks assigned by him, and user.todo as the tasks which he needs to do.

    I hope I have understood your problem correctly and the solution is what you need.
    @ PresentSoft Technologies Pvt. Ltd., a software development firm in Goa - India, we develop scalable applications using on Ruby on Rails and Android.

    My blog @ AnayKamat.com

IMN logo majestic logo threadwatch logo seochat tools logo