Rails 4 / Ruby 2:保存嵌套属性不能按预期工作

时间:2013-10-16 13:39:49

标签: ruby-on-rails ruby activerecord

我试图通过人物模型的表单保存作业模型的属性:

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的创建操作中包含第二行。但是,第一行不应该足够了,因为我已经在assignment_params中包含了assignment_params了吗?我问,因为我在使用非常相似的代码的编辑人员表单更新作业时遇到了问题。

1 个答案:

答案 0 :(得分: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对象,然后通过嵌套属性将其传递给另一个模型:)