configs/routes.rb
Shutters
并且Paints
是Jobs
.
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