Reputation: 39
Good night friends!
In a form with many through, I need to display all the objects of a given class (tool), with a checkbox field and text field next to it. My form is as follows:
= 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
But I'm getting the following error:
Undefined method `tool_id 'for # <Tool: 0x007faef0327c28>
Did you mean To_gid
Models
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
Controller
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
Thank you!
Upvotes: 0
Views: 303
Reputation: 959
the error is quite simple: tool doesn't has a tool_id
method. BUT, why are you asking this to a tool object instead of a instrumentalisation object?
So, you're trying to create some instrumentalisations
but you're passing a tool
as object:
f.simple_fields_for :instrumentalisations, **tool** do |i|
fields_for
requires a record_name
, whith in this case is :instrumentalisations
and the 2nd arg is the record_object
, which should be an instrumentalisations
object and not a tool
object.
So to fix it would have to pass an instrumentalisation
object. You can accomplish that by:
f.simple_fields_for :instrumentalisations, Instrumentalisation.new(tool: tool) do |i|
Of course this isn't the best solution since if you edit this object would be building a lot of new instrumentalisations
.
I'd recommend the cocoon gem, which makes it easier to handle nested forms!
Upvotes: 0