我正在尝试创建一个用户选择志愿者完成任务的应用。 volunteers
被视为participants
的方式是通过selected
连接表上的TaskVolunteer
布尔属性。不幸的是,当我试图找到特定类的参与者时,我收到以下错误:
task = Task.create
task.participants
SQLite3::SQLException: no such column: users.selected
模型
class User < ActiveRecord::Base
has_many :owned_tasks, class_name: "Task", foreign_key: :owner_id
has_many :task_volunteers, as: :volunteer
has_many :volunteered_tasks, through: :task_volunteers
end
class TaskVolunteer < ActiveRecord::Base
# task_id, volunteer_id, selected (boolean)
belongs_to :task
belongs_to :volunteer, class_name: "User", foreign_key: :volunteer_id
end
class Task < ActiveRecord::Base
# owner_id
has_many :task_volunteers
has_many :volunteers, through: :task_volunteers, source: :volunteer
has_many :participants, -> {where(selected: true)}, through: :task_volunteers, source: :volunteer
belongs_to :owner, class_name: "User"
end
答案 0 :(得分:2)
错误是由TaskVolunteer中的错误foreign_key
选项引起的。
belongs_to :volunteer, class_name: "User", foreign_key: :volunteer_id
foreign_key
此处指的是users
表上不在tasks_volunteers
上的列。您可以删除外键选项。
class TaskVolunteer < ActiveRecord::Base
# task_id, volunteer_id, selected (boolean)
belongs_to :task
belongs_to :volunteer, class_name: "User"
end
<强>加强>
我不得不说通过改变命名并使用枚举来表示状态,你可以非常显着地削减代码和认知复杂性。
class User < ActiveRecord::Base
has_many :participations, foreign_key: :participant_id
has_many :owned_tasks, class_name: "Task", as: :owner
end
class Task < ActiveRecord::Base
belongs_to :owner, class_name: 'User'
has_many :participations
has_many :participants, through: :participations, source: :participant
# Dynamically generates relations such as 'selected_participants'
Participation.statuses.keys.each do |status|
has_many "#{status}_participants".to_sym,
-> { where(participations: { status: status.to_sym }) },
through: :participations,
source: :participant
end
end
class Participation < ActiveRecord::Base
belongs_to :task
belongs_to :participant, class_name: "User"
enum status: [:interested, :selected]
end
枚举宏为您提供了以下内容:
user.participations.selected
participation.selected?