美文网首页
Rails 5 中 accepts_nested_attribu

Rails 5 中 accepts_nested_attribu

作者: ibob2012 | 来源:发表于2019-08-21 11:46 被阅读0次

Rails 5 中 accepts_nested_attributes_for 不起作用。

如果你在 Rails 5 中使用 accepts_nested_attributes_for并且是 has_many 的关系,那么你可能需要使用inverse_of 这个选项。

具体见下面实例

Model

有三个 model 分别为 course, section 与 assignments。

classCourse<ApplicationRecord

        has_many:sections,dependent: :destroy

        has_many:assignments,through: :sections

end

classSection<ApplicationRecord

        belongs_to:course

        has_many:assignments,dependent: :destroy

          accepts_nested_attributes_for:assignments,allow_destroy: true

end

classAssignment<ApplicationRecord

    belongs_to:section

end

Controllers

classAdmin::SectionsController<ApplicationController

        before_action:authenticate_user!

        before_action:admin_required

        def    new

                @course=Course.find(params[:course_id])

                @section=@course.sections.new

                @section.assignments.build

        end

        def  create

            @section=Section.new(section_params)

            @course=Course.find(params[:course_id])

            @section.course_id=@course.id

            if@section.save

                   redirect_to     admin_course_sections_path(@course)

              else

                     render:new

end

end

private

def    section_params

           params.require(:section).permit(:title,:content,:course_id,

                                                        assignments_attributes: [:id,:title,:content,:_destroy])

end

end

一直未能成功添加assignments

后来加上了 inverse_of 之后,马上可以了。

classSection<ApplicationRecord

            belongs_to:course

            has_many:assignments,dependent: :destroy,inverse_of: :section

            accepts_nested_attributes_for:assignments,allow_destroy: true

end

原文:https://booox.github.io/2018/06/10/rails-nested-attributes-not-working/

相关文章

网友评论

      本文标题:Rails 5 中 accepts_nested_attribu

      本文链接:https://www.haomeiwen.com/subject/nadbsctx.html