Rails accepted_nested_attributes_for不保存has_many中的关联

时间:2017-09-13 14:27:04

标签: ruby-on-rails ruby many-to-many rails-activerecord has-many-through

我正在创建project_management应用程序

当经理在那个时候创建​​项目时我也想保存开发人员, 为此,我创建了user_projects模型

但我无法创建user_projects记录

模型

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  scope :developers, ->{ where(:role => "developer") }

  has_many :developers, class_name: "User",
                        foreign_key: "manager_id"
  has_many :user_projects
  has_many :projects, through: :user_projects
  belongs_to :manager, class_name: "User", optional: true

  enum role: {developer: 0, manager: 1}

  def full_name
    [first_name, last_name].join(' ')
  end
end

class Project < ApplicationRecord
  has_many :user_projects
  has_many :users, through: :user_projects

  accepts_nested_attributes_for :user_projects, reject_if: ->(object){ object[:user_id].blank? }
end

class UserProject < ApplicationRecord
  belongs_to :user
  belongs_to :project
end

项目控制器

class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy]

  def new
    @project = Project.new
    @project.user_projects.build
  end

  def create
    @project = Project.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  private

    def project_params
      params.require(:project).permit(:project_name, :project_description, :user_projects_attributes => [:user_id => []])
    end
end

项目创建表单

<%= simple_form_for(@project, html: { class: 'form-horizontal' }) do |form| %>
  <%= form.input :project_name %>
  <%= form.input :project_description %>
  <%= form.simple_fields_for :user_projects do |user_project| %>
    <%= user_project.association :user, :collection => User.developers, :label_method => :full_name, :value_method => :id, input_html: { multiple: true }%>
  <% end %>  
  <%= form.button :submit%>
<% end %>

得到错误

  

错误禁止此项目被保存:
   1.用户项目用户必须存在    2.用户项目项目必须存在

2 个答案:

答案 0 :(得分:0)

您应该接受users的属性,而不是项目模型中users_projects的属性。这是可行的,因为您已在User和Project之间设置了has_many_through关联。

这是一个简单的例子,可以达到关键点。

class User < ApplicationRecord
  has_many :user_projects
  has_many :projects, through: :user_projects
end

class Projects < ApplicationRecord
  has_many :user_projects
  has_many :users, through: :user_projects
  accepts_nested_attributes_for :users
end

答案 1 :(得分:0)

我认为你的许可证中存在问题,试图改变它,如

user_projects_attributes: [:id]