带有check_boxes错误的simple_fields_for

时间:2017-03-10 02:33:52

标签: ruby-on-rails fields-for

晚安朋友们!

在包含很多through的表单中,我需要显示给定类(工具)的所有对象,旁边有一个复选框字段和文本字段。我的表格如下:

= 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

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

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

fields_for需要record_name,在这种情况下为:instrumentalisations,第二个arg为record_object,其中为{ {1}}对象和一个instrumentalisations对象。

因此要修复它必须传递一个tool对象。你可以通过以下方式实现这一目标:

instrumentalisation

当然,这不是最佳解决方案,因为如果您编辑此对象,则会构建大量新f.simple_fields_for :instrumentalisations, Instrumentalisation.new(tool: tool) do |i|

我推荐使用cocoon gem,这样可以更轻松地处理嵌套表单!