Home > Blockchain >  Ruby on Rails | Binding View form to model/controller
Ruby on Rails | Binding View form to model/controller

Time:08-19

This view is rendered as a partial, in a :show sidebar of other module/objects

routes:

Rails.application.routes.draw do
  devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  get '/', to: 'application#index'
  resources :commands
end

_command.html.erb:

note the form_for, some variances I've tried, with their errors:

When its: form_for @command Error: First argument in form cannot contain nil or be empty

When its: form_for Command.new Error: uninitialized constant CommandsController

<% @modName = locals[:moduleName] %>
<% @id = locals[:id] %>
<%= form_for Command.new do |f| %>
    <%= f.collection_select(:Code, Command.where(FLD: @modName), :Code, :Definition, options ={prompt: true}, html_options = {:onchange => "updateSubMod(this.value)"}) %>
    <br /><br />
    <%= f.submit %>
<% end %>

Relevant controller snippet:

ActiveAdmin.register Command do
  menu false

  all_fields = Commands.fields
  all_fields = all_fields   [:mod, :id, :submod]
  permit_params all_fields 
  field_special = Commands.types
  
  controller do
    def new
      @command = Command.new
      @resource = Command.new
    end
  end

Rake Routes:

GET              /commands(.:format)           commands#index
POST             /commands(.:format)           commands#create
new_command GET  /commands/new(.:format)       commands#new
edit_command GET /commands/:id/edit(.:format)  commands#edit
command GET      /commands/:id(.:format)       commands#show
PATCH            /commands/:id(.:format)       commands#update
PUT              /commands/:id(.:format)       commands#update
DELETE           /commands/:id(.:format)       commands#destroy

UPDATE: my (new) app/controllers/commands_controller.rb

class CommandsController < ApplicationController
    def new
    @command = Command.new
    end
    
end

Any insight, much appreciated.

CodePudding user response:

Following the error messages, I conclude that:

  1. @command is not defined. Because when you put Command.new in the view, the changed error message suggests that it fixes that particular problem. Revealing a different one! (So either put Command.new in the form_for helper, or define @command = Command.new in the controller.

  2. The second problem (CommandsController not defined). Well Rails 7 has a particular way of organizing files, and it's pretty opinionated about that. It's implemented by the zeitwerk gem. You are urged to "fall-in" with the "Rails way", and put the CommandsController class in the app/controllers/commands_controller.rb file.

  • Related