连接表中的属性没有这样的列

时间:2015-06-21 22:57:30

标签: ruby-on-rails activerecord attributes associations jointable

我正在尝试创建一个用户选择志愿者完成任务的应用。 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

1 个答案:

答案 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?