Rails association with multiple foreign keys

前端 未结 6 1737
情深已故
情深已故 2020-11-28 02:21

I want to be able to use two columns on one table to define a relationship. So using a task app as an example.

Attempt 1:

class Use         


        
6条回答
  •  失恋的感觉
    2020-11-28 02:59

    I worked out a solution for this. I'm open to any pointers on how I can make this better.

    class User < ActiveRecord::Base
    
      def tasks
        Task.by_person(self.id)
      end 
    end
    
    class Task < ActiveRecord::Base
    
      scope :completed, -> { where(completed: true) }   
    
      belongs_to :owner, class_name: "User", foreign_key: "owner_id"
      belongs_to :assignee, class_name: "User", foreign_key: "assignee_id"
    
      def self.by_person(user_id)
        where("owner_id = :person_id OR assignee_id = :person_id", person_id: user_id)
      end 
    end
    

    This basically overrides the has_many association but still returns the ActiveRecord::Relation object I was looking for.

    So now I can do something like this:

    User.first.tasks.completed and the result is all completed task owned or assigned to the first user.

提交回复
热议问题