1

我正在创建一个管理用户和任务的应用程序。这两个模型之间的关系是多对多的,因为一个用户可以有很多任务分配给他们,而一个任务可以有很多用户分配给它。出于这个原因,我创建了一个 UserTasks 迁移和模型来充当连接表。展望未来,我意识到我希望我的前端功能能够让用户能够从给定任务中分配和删除用户。由于我使用的是 JS 前端,并向我的 Rails 服务器控制器发送 AJAX 请求,因此我不清楚如何处理此功能。我不想从数据库中删除用户或任务,而只是关系。可以为我的 UserTask 模型制作一个 API 控制器,并在 #destroy 方法中处理这个逻辑吗?Rails 提供了更自动化的方法吗?

这是我的模型的样子:

用户

class User < ApplicationRecord
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i

  after_initialize :ensure_session_token

  validate :valid_email

  validates :name, :email, :password_digest, :session_token, presence: true
  validates :email, :session_token, uniqueness: true
  validates :password, length: { minimum: 6, allow_nil: true }

  has_many :user_tasks,
  foreign_key: :user_id,
  class_name: "UserTask"

  has_many :tasks,
  through: :user_tasks,
  source: :task

  ...misc code
end

任务

class Task < ApplicationRecord
  validates :name, presence: true

  has_many :user_tasks,
  foreign_key: :task_id,
  class_name: "UserTask"

  has_many :assignees,
  through: :user_tasks,
  source: :user

  has_many :sub_tasks,
  foreign_key: :parent_task_id,
  class_name: "Task"
end

用户任务

class UserTask < ApplicationRecord
  validates :user_id, :task_id, presence: true

  belongs_to :user,
  foreign_key: :user_id,
  class_name: "User"

  belongs_to :task,
  foreign_key: :task_id,
  class_name: "Task"
end

当前路线

Rails.application.routes.draw do
  root to: 'static_pages#root'

  namespace :api, defaults: { format: 'json' } do
    resources :users, only: [:create, :update, :show]
    resources :tasks, only: [:create, :index, :show, :update, :destroy]
    resources :projects, only: [:create, :index, :show, :update, :destroy]
    resource :session, only: [:create, :destroy]
  end
end
4

1 回答 1

0

Rails 提供了:has_many通过父记录管理记录的能力。

例如,您可以使用 allow_destroy: true 选项允许用户接受_nested_attributes_for :user_tasks。

class User < ActiveRecord::Base
  accepts_nested_attributes_for : user_tasks, allow_destroy: true
end

在这样的配置之后,您可以通过用户记录update操作添加/销毁嵌套属性。

params = {
  id: 'user_id', user_tasks_attributes: [
    { user_id: 'user_id', task_id: 'task_id' }, #this will create new join record
    { id: 'user_task_id', _destroy: '1' } #this will destroy join record
  ]
}

但我会为 UserTasks创建一个单独的控制器

阅读文档以获取更多信息。

于 2018-09-16T09:40:08.923 回答