我在许多线程中看到了未定义的局部变量,也看到了很多添加关系,所以请在建议在其他地方回答之前阅读问题。(当然,如果您确实在其他地方找到了答案,我将不胜感激)
这些表是服务和检查(在车库的上下文中,服务是类型,检查是任何特定服务需要执行的)。这是多对多的,所以我通过关系建立了很多。
问题是,尽管一切正常,但我仍然收到错误消息:
未定义的局部变量或方法“check_ids”
线:
@service.service_checks.build(check_id: check_ids, service_id: @service.id )
我为定义变量所做的任何尝试似乎都会阻止这些关系起作用。这让我对如何让一切和谐运作一无所知。
楷模:
class Service < ActiveRecord::Base
has_many :service_checks, :dependent => :destroy
has_many :checks, :through => :service_checks
#attr_accessor :check_ids
accepts_nested_attributes_for :checks
accepts_nested_attributes_for :service_checks
end
class Check < ActiveRecord::Base
has_many :service_checks
has_many :services, :through => :service_checks
belongs_to :check_cat
end
class ServiceCheck < ActiveRecord::Base
belongs_to :service, dependent: :destroy
belongs_to :check, dependent: :destroy
accepts_nested_attributes_for :check, :reject_if => :all_blank
self.primary_key = [:service_id, :check_id]
end
我在 Service 中的更新功能如下所示:
def update
respond_to do |format|
if @service.update(service_params)
# This builds the relationships
@service.service_checks.build(check_id: check_ids, service_id: @service.id )
format.html { redirect_to @service, notice: 'Service was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @service.errors, status: :unprocessable_entity }
end
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def service_params
params.require(:service).permit(:name, :price, :check_ids => [])
end
我的表格很简单:
<%= f.association :checks,
as: :check_boxes,
label_method: :name,
value_method: :id,
label: 'Checks' %>