5

configs/routes.rb Shutters并且PaintsJobs.

resources :jobs do
    resources :shutters
    resources :paints
end

app/models/job.rb AJob包含很多Shutters很多Paints.

class Job < ActiveRecord::Base
    has_many :shutters, dependent: :delete_all
    has_many :paints, dependent: :delete_all

    accepts_nested_attributes_for :shutters, allow_destroy: true, :reject_if => lambda { |a| a[:no].blank? }
    accepts_nested_attributes_for :paints, allow_destroy: true, :reject_if => lambda { |a| a[:name].blank? }`

app/models/shutter.rb 包含Shutter属于 oneJob和 one Paint

class Shutter < ActiveRecord::Base
    belongs_to :job
    belongs_to :paint

app/models/paint.rb APaint属于一个Job,但可以被Shutters该工作中的许多人引用。

class Paint < ActiveRecord::Base
    belongs_to :job
    has_many :shutters

如果数据库中没有代码,两者都Jobs#show可以正常工作。但是在添加油漆的那一刻,会引发 RuntimeError,“在自动加载常量 PAINT 时检测到循环依赖”。Jobs#edit<%= debug @job.paints %>Paints

解决此错误的最佳方法是什么?

编辑:控制器信息

应用程序/控制器/jobs_controller.rb

class JobsController < ApplicationController
    before_action :set_job, only: [:show, :edit, :update, :destroy]

    ...

    # GET /jobs/1
    # GET /jobs/1.json
    def show
    end

    # GET /jobs/new
    def new
        @job = Job.new
        @job.shutters.build
        @job.paints.build
    end

    # GET /jobs/1/edit
    def edit
        @job.shutters.build
        @job.paints.build
    end

应用程序/控制器/shutters_controller.rb

class ShuttersController < ApplicationController
    def new
        @shutter = Shutter.new
    end

    def destroy
        @shutter = Shutter.find(params[:id])
        @job = Job.find(@shutter[:job_id])
        @shutter.destroy
        respond_to do |format|
            format.html {redirect_to @job, notice: 'Shutter was succesfully deleted.' }
        end
    end
end

应用程序/控制器/paints_controller.rb

class PaintsController < ApplicationController
    def new
        @paint = Paint.new
    end

    def destroy
        @paint = Paint.find(params[:id])
        @job = Job.find(@paint[:job_id])
        @paint.destroy
        respond_to do |format|
            format.html {redirect_to @job, notice: 'Paint was succesfully deleted.' }
        end
    end
end
4

1 回答 1

15

问题都不是这些。实际上,我的Paint模型包含一个名为 的字段:type,它是元分类或类似的保留关键字。谢天谢地,得到了好心人的帮助#RubyOnRails,否则像我这样的新手会尝试从头开始,遇到同样的问题,而且永远也想不通。希望这对未来的 Google 员工有所帮助。提前付款!

于 2014-05-26T21:07:45.213 回答