1

我正在尝试通过人员模型的表单保存分配模型的属性:

class Person < ActiveRecord::Base
  has_one :assignment, dependent: :destroy
  accepts_nested_attributes_for :assignment, allow_destroy: true
end

class Assignment < ActiveRecord::Base
  belongs_to :person
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :reverse_assignments, class_name:  'Assignment'
end

class PersonsController < ApplicationController
  def new
    @person = Person.new
  end

  def create
    @person = Person.build(person_params)
    @person.build_assignment(assignment_params) # Shouldn't this be obsolete?
    redirect_to root_url
  end

  private

    def person_params
      params.require(:person).permit(:name, assignment_attributes: [:id, :project_id])
    end

    def assignment_params
      params.require(:assignment).permit(:person_id, :project_id) # Only needed because of the "obsolete" line
    end
end

class AssignmentsController < ApplicationController
end

这是表单(slim-html):

= form_for(@person) do |f|
  = f.text_field :name
  = fields_for :assignment do |r|
    = r.collection_select :project_id, Project.order(:name), :id, :name
  = f.submit 'Save'

通过项目表单创建分配是可行的,但只能通过在 PersonsController 的创建操作中包含第二行。但是,第一行是否足够,因为我已经在 person_params 中包含了 assignment_params?我在问,因为我在通过使用非常相似的代码的编辑人员表单更新作业时遇到问题。

4

1 回答 1

2
= form_for(@person) do |f|
  = f.text_field :name
  = f.fields_for :assignment do |r|
    = r.collection_select :project_id, Project.order(:name), :id, :name
  = f.submit 'Save'

尝试添加f.fields_for

您可能还想将此添加到您的“新”操作中:

def new
   @person = Person.new
   @person.build_assignment
end

这将为分配构建 ActiveRecord 对象,然后通过嵌套属性将其传递给另一个模型:)

于 2013-10-16T14:07:52.507 回答