Reputation:
I have many to many association through UserTask table. I need to get user with type creator from task (task.creator). It should be like task.user_tasks.where(user_type: 0) but with rails associations. Is it possible?
Here is my User model
class User < ApplicationRecord
has_many :user_tasks, foreign_key: 'user_email', primary_key: 'email'
has_many :tasks, through: :user_tasks
end
Here is my Task model
class Task < ApplicationRecord
has_many :user_tasks, dependent: :destroy
has_many :users, through: :user_tasks
end
Here is my UserTask model
class UserTask < ApplicationRecord
belongs_to :user, foreign_key: 'user_email', primary_key: 'email'
belongs_to :task
enum user_type: [:creator, :allowed]
end
Upvotes: 0
Views: 54
Reputation: 23671
You can get it using
User.joins(:user_tasks).where(user_tasks: { user_type: 0 })
Upvotes: 2