2017-03-10 83 views
0

晚安的朋友!simple_fields_for with check_boxes error

在一个有很多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 

谢谢!

+0

事实上,这个字段:tool_id是一个外键会干扰什么? – wilfrank

+0

我注意到,当我从 '= f.simple_fields_for改变:instrumentalisations,工具做| I |' 到 '= f.simple_fields_for:instrumentalisations做| I |' 介绍了我几个工具对象,它似乎是重复的 – wilfrank

回答

0

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

所以,你想创造一些instrumentalisations但你传递一个tool作为对象:

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

fields_for需要record_name,蒙山在这种情况下是:instrumentalisations和第二ARG是record_object,其中应该是instrumentalisations对象并且不是 a tool对象。

所以要解决它将不得不通过一个instrumentalisation对象。您可以实现通过:

f.simple_fields_for :instrumentalisations, Instrumentalisation.new(tool: tool) do |i| 

当然这并不是因为如果你编辑这个对象将被建设了很多新的instrumentalisations的最佳解决方案。

我推荐的cocoon gem,这使得它更容易处理嵌套形式!

+0

其实,这不是我所需要的。我想显示工具类的所有对象,用复选框字段标记它们,并显示另一个文本字段以附加项目数量。在那种情况下,茧宝石不会解决我的问题。 [这里本文](http://millarian.com/rails/quick-tip-has_many-through-checkboxes/),提出了一些亲如我在寻找,但我需要添加一个字段,并使用[simple_form gem](https://github.com/plataformatec/simple_form)。 – wilfrank

+0

错误在于您正在将工具对象传递到工具化循环中。 使用fields_for传递一个新的工具化只是你能存档你试图做的方法之一。 – dpedoneze

相关问题