Rails association with multiple foreign keys

前端 未结 6 1746
情深已故
情深已故 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:58

    Extending upon @dre-hh's answer above, which I found no longer works as expected in Rails 5. It appears Rails 5 now includes a default where clause to the effect of WHERE tasks.user_id = ?, which fails as there is no user_id column in this scenario.

    I've found it is still possible to get it working with a has_many association, you just need to unscope this additional where clause added by Rails.

    class User < ApplicationRecord
      has_many :tasks, ->(user) {
        unscope(:where).where(owner: user).or(where(assignee: user)
      }
    end
    

提交回复
热议问题