Rails HABTM关系不匹配

时间:2019-08-11 09:36:48

标签: ruby-on-rails database relationship

我试图为我的项目模型建立HABTM关系,但由于此错误privacy.file_unique_origin和描述false,我无法保存它,但我没有弄错。正如我在日志中看到的那样,ActiveRecord::AssociationTypeMismatch in ProjectsController#update中每次都有一个空条目,我也不知道为什么。也许任何人都可以帮助我。

这是我的项目模型:

DockerService(#47111788307900) expected, got "" which is an instance of String(#47111734410780)

我的DockerServicesProjects模型

project_params[:docker_service]

和我的DockerService模型

class Project < ApplicationRecord
  # belongs to
  belongs_to :user

  # has_many
  has_many :docker_services_projects
  has_many :docker_services, through: :docker_services_projects

  ...
end
我的ProjectsController中的

project_params:

class DockerServicesProject < ActiveRecord::Base
  belongs_to :docker_service
  belongs_to :project
end

我的表单有这个:

class DockerService < ApplicationRecord
  has_many :docker_services_projects
  has_many :projects, through: :docker_services_projects
end

def project_params
      params.require(:project).permit(
        :user_id,
        :title,
        :description,
        :config,
        docker_services: [],
        documents: []
      )
    end

更新方法如下:

<%= form_with(model: project, local: true) do |form| %>

在保存模型之前记录参数时,我在project_params中得到了它:

<div class="field">
  <%= form.select :docker_services, options_from_collection_for_select(DockerService.all, :id, :title), {}, { multiple: true } %>
</div>

1 个答案:

答案 0 :(得分:1)

必须更改选择字段名称,也需要在控制器中更改字段名称。它应该是 docker_service_ids 而不是docker_services:

# _form.html.erb

<div class="field">
  <%= form.select :docker_service_ids, options_from_collection_for_select(DockerService.all, :id, :title), {}, { multiple: true } %>
</div>

# projects_controller.rb
def project_params
  params.require(:project).permit(
    :user_id,
    :title,
    :description,
    :config,
    docker_service_ids: [],
    documents: []
  )
end