Error encountered while attempting to render a form within a partial in Rails 5: "simple_fields_for" method is not defined for the SimpleForm::FormBuilder instance

This is a continuation from this thread: Passing a form as a local to a ajax rendered partial in Rails 5

I've searched extensively but haven't been able to find a working solution.

Relevant Controller (profits_controller.rb):

def new_tabs
    @market = Market.order('mjsnumber').all.first
    @profit = Profit.new
    profit_types_markets_products
end

def fetch_market
    @market = Market.where(:id => params[:market_id]).first
    @form = params["form"]
    respond_to do |format|
        format.js { render layout: false}
    end
end

Relevant View (new_tabs.html.erb):

<%= simple_form_for @profit, :remote => true do |form| %> 
<% @markets.each_with_index do |market, i| %>
     <%= link_to market.nick, fetch_market_path(:market_id => market.id, :form => form, profit: @profit), :remote=>'true', :id => 'navBtn' + market.id.to_s, :class => 'd-flex flex-grow-1 align-content-center text-center nav-item nav-link ' + active(i).to_s + profit_nav_font_color(market.color).to_s, "data-toggle" => "pill", "roll" => "tab", "style" => "background-color: " + market.color.to_s + ";", remote: true %>
<% end %>
<%= render :partial => 'edit_partial_form', locals: { market: @market, form: form, profit: @profit } %>

Relevant Partial (_edit_partial_form.html.erb):

<%= market.namae %>
<%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
    <%= figures_form.input "[test]" %>
<% end %>

Relevant JS (fetch_market.js.erb):

$("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: @market, form: @form, profit: @profit } ) %>");

Routes:

resources :profits do
    resources :markets
    resources :products
    collection do
        get 'new_by_product_type'
        get 'new_tabs'
    end
end
get "/fetch_market" => 'profits#fetch_market', as: 'fetch_market'
patch 'profits/:id/autosave', as: :autosave_profit, to: 'profits#autosave'

The partial renders correctly and the links seem to have the FormBuilder information. However, when I click the link, it shows the params in the controller but then encounters an error while loading the partial in the console:

ActionView::Template::Error (undefined local variable or method `form' for #<#<Class:0x00007fdbd6453648>:0x00007fdbd68db5f8>
Did you mean?  fork):
    1: $("#edit_partial_form").html("<%= escape_javascript(render partial: 'edit_partial_form', locals: { market: @market, form: form, profit: @profit } ) %>");

In my local environment, I receive the following full error message when clicking on the link for the second market in the list of generated markets:

Processing by ProfitsController#fetch_market as JS
  Parameters: {"form"=>"#<SimpleForm::FormBuilder:0x00007fed50dba9f8>", "market_id"=>"2"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ /home/mudl/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  Market Load (0.3ms)  SELECT  "markets".* FROM "markets" WHERE "markets"."id" = $1 ORDER BY "markets"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/profits_controller.rb:75
  Rendering profits/fetch_market.js.erb
  Rendered profits/_edit_partial_form.html.erb (6.5ms)
  Rendered profits/fetch_market.js.erb (7.5ms)
Completed 500 Internal Server Error in 12ms (ActiveRecord: 0.6ms)



ActionView::Template::Error (undefined method `simple_fields_for' for "#<SimpleForm::FormBuilder:0x00007fed50dba9f8>":String):
    11:                                 MJS 番後: <%= market.mjsnumber %>
    12:                         </span>
    13:                 </div>
    14:                 <%= form.simple_fields_for :figures, :defaults => { :input_html => { :class => "floatTextBox" }}, remote: true do |figures_form| %>
    15:                         <%= figures_form.input "[test]" %>
    16:                 <% end %>
    17:

app/views/profits/_edit_partial_form.html.erb:14:in `_app_views_profits__edit_partial_form_html_erb__249336059151108365_70328546926840'
app/views/profits/fetch_market.js.erb:1:in `_app_views_profits_fetch_market_js_erb___2023159631102932010_70328546933900'
app/controllers/profits_controller.rb:78:in `block (2 levels) in fetch_market'
app/controllers/profits_controller.rb:77:in `fetch_market'
(undefined method `simple_fields_for' for "#<SimpleForm::FormBuilder

I have removed the simple_form tag because even after changing it to a regular form during testing, the error persists with any method I call after field_for in the partial.

Thank you in advance.

EDIT:

I ultimately gave up and resorted to using the @profit variable to create a new form in the partial (not ideal, but functional). However, I am still curious if the original approach is achievable, so I will keep the question open.

Answer №1

Before anything else, ensure that you close your form block. If you are unable to pass the form to a partial, consider trying to accomplish it without using a partial.

<%= simple_form_for @profit, remote: true do |form| %> 
  <% @markets.each_with_index do |market, i| %>
     <%= link_to market.nick, fetch_market_path(market_id: market.id, form: form, profit: @profit), id: 'navBtn' + market.id.to_s, class: 'd-flex flex-grow-1 align-content-center text-center nav-item nav-link ' + active(i).to_s + profit_nav_font_color(market.color).to_s, "data-toggle" => "pill", "roll" => "tab", "style" => "background-color: " + market.color.to_s + ";", remote: true %>
     <%= market.name %>
  <% end %>
  <%= form.simple_fields_for :figures, something_key: "value", remote: true do |figures_form| %>
    <%= figures_form.input "[test]" %>
   <% end %>
<% end %>

It is recommended to use something_key: "value" instead of :something_key => "value".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmitting JSON information via Ajax to an Express server

I'm encountering an issue trying to pass JSON data from the client side to the express server. When I run the code below, it returns a 400 error (bad request). // Client Side $.ajax({ type:"post", url:"/name", dataType: 'json', ...

Upon script load, a random item from an array will be displayed and recorded in a separate array

I'm working on a fun code project where I aim to display random animal names in different colors that change when a specific keyboard key is pressed. The challenge I'm facing is that the first random animal name in a random color only appears aft ...

What is the Dojo counterpart for jQuery's .live() function?

Is there a Dojo alternative to jQuery .live() function? http://api.jquery.com/live/ In my search, the only workaround I came across was to disconnect the event handlers in Dojo and then reconnect them when new dynamic content is added to the page. ...

What is the best way to handle sequential $http calls in AngularJS? Specifically, I want to make the second $http call dependent on the response of the first

When making two $http calls, the second call should only be executed based on the response from the first call if there is an error present. ...

Modifying the input placeholder color with ng-style

I am working on setting the color of my input placeholder using a dynamic color defined in a $scope variable in my controller for my HTML code. The $scope variable is structured as follows: $scope.primaryColor={"color":colorVar}; //colorVar represents th ...

How can I create a unique CSS or JS transition for a button that dynamically changes size based on text

My Angular app features a button labeled with "+". When the user hovers over it, I use element.append(' Add a New Number'); to add the text "Add a New Number" next to the + sign in the label. Upon clicking the button, a new number is added and ...

A yearly overview calendar

My current need is: I am looking for a calendar (wall plan) that covers the entire year and can display my events stored in the database. Is there any freely available control that offers a year view feature? I have looked into various options but only ...

Dynamic Loading of Hovercards using jQuery AJAX

I've been working on integrating jQuery hovercard into our web application, specifically to display HTML content retrieved from an AJAX page when a user hovers over a username link with the data attribute data-toggle="user". Here's what our code ...

keeping a myriad of characteristics within one set of data

I am in the process of designing a system with a model and table named 'product'. Each product is expected to have roughly 100 attributes, where each attribute will be stored as a string. I am unsure whether it would be best to simply add all the ...

Is it possible for the controller of a modal window to have access to functions within the parent controller

If you were to launch a modal window using $modal.open from an angular directive, would the modal window be able to access functions defined within the parent directive? Below is the code for the directive controller: function parentFunction() { re ...

Angular Unit Testing: Executing Multiple expectGET's within a Singular Test

I am facing an issue with a unit test that fails to read the JSON in the second request properly This is my implementation of the Config factory (function() { 'use strict'; angular.module('commercial.factories').factory(&apos ...

Input the date manually using the keyboard

I am currently utilizing the rc calendar package available at https://www.npmjs.com/package/rc-calendar When attempting to change the year from 2019 to 2018 by removing the "9," it works as expected. However, when trying to delete the entire date of 1/15/2 ...

Choose a select few checkboxes and then disable the remaining checkboxes using Vue and Laravel

I'm currently working on a project using Laravel 10 and Vue3. In the form, users are allowed to select only 3 checkboxes. Once they have selected 3 checkboxes, all remaining checkboxes should be disabled. I attempted to implement this functionality a ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

Exploring the power of Foundation For Apps and Angular by seamlessly displaying dynamic data sourced from

I'm currently working with Foundation for Apps, a framework that incorporates elements of AngularJS. My goal is to display the content from a local JSON file by accessing it through a controller and rendering the results as 'cards'. Addition ...

JavaScript basic calculator app failed to generate an error as anticipated

For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown. Initially, concern ...

How to properly align TableHeader and TableBody contents in a Material-UI table

I am experiencing an issue with a file that is supposed to display a table of data pulled from a database. Although the table does appear, all the data seems to be displayed under the ISSUE NUMBER column, instead of being aligned with their respective col ...

Adjusting the Connection header in a jQuery ajax request

I've been attempting to modify the Connection header using the code below, but so far, I haven't had any success jQuery.ajax({ url: URL, async: boolVariable, beforeSend: function(xhr) { xhr.setRequestHeader("Connection ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Is it possible to capture and generate an AxiosPromise inside a function?

I am looking to make a change in a function that currently returns an AxiosPromise. Here is the existing code: example(){ return api.get(url); } The api.get call returns an object of type AxiosPromise<any>. I would like to modify this function so ...