simple_fields_ for带有check_boxes错误



晚安朋友!

在许多过程中,我需要显示给定类(工具)的所有对象,旁边的复选框字段和文本字段。我的形式如下:

= simple_form_for @service, html: { class: 'form-horizontal' } do |f|
   - @tools.each do |tool|
      = f.simple_fields_for :instrumentalisations, tool do |i|
         = i.input :tool_id, tool.id, as: :check_boxes
         = i.input :amount

但是我会收到以下错误:

 Undefined method `tool_id 'for # <Tool: 0x007faef0327c28> 
 Did you mean To_gid

型号

class Service < ApplicationRecord
   has_many :partitions, class_name: "Partition", foreign_key: "service_id"
   has_many :steps, :through => :partitions
   has_many :instrumentalisations
   has_many :tools, :through => :instrumentalisations
   accepts_nested_attributes_for :instrumentalisations
end
class Tool < ApplicationRecord
   has_many :instrumentalisations
   has_many :services, :through => :instrumentalisations
   accepts_nested_attributes_for :services
end
class Instrumentalisation < ApplicationRecord
   belongs_to :service
   belongs_to :tool
end

控制器

def new
   @service = Service.new
   @service.instrumentalisations.build
end
def edit
   @tools = Tool.all
end
def create
   @service = Service.new(service_params)
   respond_to do |format|
      if @service.save
         format.html { redirect_to @service, notice: 'Service was successfully created.' }
         format.json { render :show, status: :created, location: @service }
      else
         format.html { render :new }
         format.json { render json: @service.errors, status: :unprocessable_entity }
      end
    end
  end
 def service_params
    params.require(:service).permit(:name, :description, :price, :runtime, :status, step_ids: [], instrumentalisations_attributes: [ :id, :service_id, :tool_id, :amount ])
 end

谢谢!

错误非常简单: tool 没有tool_id方法。但是,您为什么要问一个工具对象而不是仪器化对象?

所以,您正在尝试创建一些instrumentalisations,但是您将tool作为对象传递:

f.simple_fields_for :instrumentalisations, **tool** do |i|

fields_for需要一个 record_name,在这种情况下为 :instrumentalisations,第二个arg是 record_object应该instrumentalisations对象,而不是 a tool对象。p>为了修复它必须通过instrumentalisation对象。您可以通过:

来实现这一目标
f.simple_fields_for :instrumentalisations, Instrumentalisation.new(tool: tool) do |i|

当然,这不是最好的解决方案,因为如果您编辑此对象将构建许多新的instrumentalisations

我推荐Cocoon Gem,这使得处理嵌套表单变得更容易!

相关内容

  • 没有找到相关文章

最新更新