how to handle form_for in rails namspaced controller - ruby-on-rails

I have worked with rails scaffold to generate forms and views automatically.
But now I had to use namespaced controller with model in root namspace.
So, I generated controller manually without scaffold, I'm having trouble working with form.
I suppose that the following code should generate a form for namespaced controller
<%= form_for #menu do |f| %>
<div class="field">
<%= f.label :label %><br />
<%= f.text_field :label %>
</div>
<div class="field">
<%= f.label :order %><br />
<%= f.text_field :order %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
but it doesnt. it says
undefined method `model_name' for NilClass:Class
it seems very easy to do rails with scaffold generators, but if one wants to do manually, rails helper method turns negative on them.
I have searched for form_for documentation and changed the code to
<%= form_for #menu, :url => admin_menu_path do |f| %>
then it shows a different error that
No route matches {:action=>"show", :controller=>"admin/menus"}
my rake routes gives the following output
admin_root /admin(.:format) admin/menus#index
admin_menus GET /admin/menus(.:format) admin/menus#index
POST /admin/menus(.:format) admin/menus#create
new_admin_menu GET /admin/menus/new(.:format) admin/menus#new
edit_admin_menu GET /admin/menus/:id/edit(.:format) admin/menus#edit
admin_menu GET /admin/menus/:id(.:format) admin/menus#show
PUT /admin/menus/:id(.:format) admin/menus#update
DELETE /admin/menus/:id(.:format) admin/menus#destroy
correct me if I'm wrong, but I think ruby cannot find model Menu in Admin namespace, which is obvious. So, I tried with ::Menu.new , I thought it would look up in upper namespace, but no result!

You might be forgetting to instantiate #menu in your controller.
The message "undefined method 'model_name' for NilClass:Class" says that #menu is nil.
Since admin_menu_path needs a Menu instance, Rails cannot generate the route correctly when nil is passed.
Once you have the instance variable properly set in your controller you can use:
form_for [:admin, #menu] do |f| ... end

Something like form_for [:admin, #menu] do |f| ... end should work. Similar question here: Nested resources in namespace form_for

Related

How to Pass Form Field Values to a Different Controller View in Rails?

In my Rails 6 app, I have a Product and Order model.
On my products#show page, I have some fields and a button. What I need to do is send the info to the orders#new page so that this data is shown on the orders#new page.
I have tried to write some code based on Pass variables without model associations in Rails and how to pass parameters in params using form_tag method in rails, but my code seems completely wrong.
on products#show:
<%= form_tag(new_order_path do |form| %>
<%= form.input_field :comments %>
<%= form.button %>
<% end %>
With this code I get undefined method text_field' for nil:NilClass`.
I have tried adding attr_accessor :comments to both the Product and Order model, but it doesn't help.
I don't think that my approach or what I am trying to code is right. I was just trying to piece together parts from these answers.
Can someone please help me figure out the best way I can pass this data to Orders#new to show in that view?
<%= form_with url: "/search", method: :get do |form| %>
<%= form.label :query, "Search for:" %>
<%= form.text_field :query %>
<%= form.submit "Search" %>
<% end %>
from the docs
https://guides.rubyonrails.org/form_helpers.html
and the show path also requires an id

in rails difference between form_for #article and form_for :article

im new to ruby on rails, abit confused between the usage of the following when i try to update a record:
<%= form_for #article, url:{action: "update"} do |form| %>
this one works, but i dont understand how come the submit button says 'update article'
<%= form_for :article, url:{action: "update"} do |form| %>
this one throws No route matches [POST] "/articles/2", and the submit button says 'save article'
finally:
<%= form_with(model: #article) do |form| %>
actually updates the record, but i dont understand why it's calling update, and not other methods
form_for(#article) creates a form builder which is bound to a model instance.
If #article is nil it will raise an error.
If the instance is a new record the form will use method="POST" and action="/arcticles".
If the record has been persisted it will have method="PATCH" and action="/arcticles/:article_id".
Rails derives the URL for the action attribute based on convention over configuration. So there is no need to explicitly pass the url option if you follow the conventions.
An example of this would be:
<% #article = Article.new(title: 'Hello World') %>
<%= form_for(#article) do |f| %>
<%= f.text_input :title %>
<% end %>
This will render something like:
<form action="/articles" method="POST">
<input type="text" name="article[title]" value="Hello World"/>
...
</form>
<%= form_for #article, url:{action: "update"} do |form| %> this one
works, but i dont understand how come the submit button says 'update
article'
The form builder knows it is updating an record by calling .new_record? on the the record you passed to form_with. You can change the default value of the submit button by providing translations:
# config/locales/en.yml
en:
helpers:
submit:
create: "Save new record"
update: "Save changes"
form_for(:article) creates a scoped form builder that does not wrap an object.
This creates a form builder where the inputs will be "scoped". For example:
<%= form_for(:article) do |f| %>
<%= f.text_input :title %>
<% end %>
This will render something like:
<form action="/articles" method="POST">
<input type="text" name="article[title]"/>
...
</form>
Rails derives the URL for the action attribute based on convention over configuration.
In your case <%= form_for :article, url:{action: "update"} do |form| %> causes a routing error since form_for defaults to method: "POST".
form_with is the Rails 5.1 replacement for form_for and form_tag
form_with will replace the form_for and form_tag methods which are closely related yet have very different signatures. form_for and form_tag have been soft depreciated and are slated for removal.
The idea is to provide a single method with a more consistent signature.
If you are using Rails 5.1+ this is what you should be using.
See:
Rails Guides - Action View Form Helpers
Rails API - ActionView::Helpers::FormHelper
Rails 5.1's form_with vs. form_tag vs. form_for
It all depends on #artical. If #artical is new object (id in #artical is nil) is call the create action. If #artical is existing object then it called the update method.

Rails NoMethodError

I'm having an issue very similar to the one asked in this question here: NoMethodError / undefined method `foobar_path' when using form_for However the answer there confuses me.
I went through Michael Hartel's Ruby on Rails tutorial before developing the application I'm working on at the moment, I tried to copy exactly what he did when he created a user model as I created my model. My application is designed to be a database for university professors, so the model I'm using is called "professor" but it's the same concept as "user".
Here is the code for my New.html.erb where is where users go to create a new professor:
<%provide(:title, 'Add a professor') %>
<div class="jumbotron">
<h2> New Professor</h2>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for (#professor) do |f| %>
<%= f.label "First Name" %>
<%= f.text_field :fname %>
<%= f.label "Last Name" %>
<%= f.text_field :lname %>
<%= f.label "School" %>
<%= f.text_field :school %>
<%= f.submit "Add this professor", class: "btn btn-primary" %>
<% end %>
</div>
</div>
</div>
And then here is the code from the Professor_controller.rb
class ProfessorController < ApplicationController
def show
#professor = Professor.find(params[:id])
end
def new
#professor = Professor.new
end
end
When I replace
<%= form_for (#professor) do |f| %>
In new.html.erb with:
<%= form_for (:professor) do |f| %>
It works. The thread I mentioned above said something about adding a route for the controller. My routes.rb looks like this:
Rails.application.routes.draw do
root 'static_pages#home'
get 'about' => 'static_pages#about'
get 'newprof' => 'professor#new'
resources :professor
And I don't believe that in Michael Hartel's book he does anything differently. I'm still very new to Rails so forgive me if this is a bit of an easy question, I've been stuck on it for a few days and I've tried numerous work arounds, using the instance of :professor works but #professor does not and I don't know why.
Within the Rails environment it's very important to be aware of the pluralization requirements of various names. Be sure to declare your resources as plural:
resources :professors
Declaring it in the singular may mess up the automatically generated routes, you'll get thing like professor_path instead of professors_path. You can check what these are with:
rake routes
If you get errors about x_path being missing, check that there's a route with the name x in your routes listing. The most common case is it's mislabeled, a typo, or you've failed to pluralize it properly.

Rails 3 routing not generating proper paths for new vs edit views

I'm getting some funkiness that is absolutely confounding me with Rails 3. I can't seem to get the routing to generate the proper path using the (mostly) standard _form style of the scaffold.
First off, I'm doing everything within an "admin" namespace. I'm finding that the form partial throws a routing error if I use admin_team_path(#team) to generate the path when creating a new Team, but then submitting the form when editing, it throws an error unless I use admin_teams_path.
admin_team_path(#team) where #team = Team.new throws this error:
No route matches {:controller=>"admin/teams", :action=>"show", :id=>#}
Meanwhile...
admin_teams_path(#team) where #team = throws this error:
The action 'edit' could not be found for TeamsController
In the latter case, it seems to be directing to the URL: http://localhost:3000/teams/1/edit - it's not recognizing the namespace properly.
Here's my full _form.html:
<%= semantic_form_for(#team, :url => admin_teams_path(#team)) do |f| %>
<%= f.semantic_errors %>
<%= f.inputs do %>
<%= f.input :user_id %>
<%= f.input :league_id %>
<%= f.input :name %>
<% end %>
<%= f.buttons do %>
<%= f.commit_button :button_html =>{:class => "primary"} %>
<% end %>
<% end %>
What gives? What's the right way to create this form partial so it works for both new and edit actions?
Namespaces seem to be such a mess to work with.
Presuming you have defined your routes in a RESOURCEful manner, like so:
namespace :admin do
resources :teams
end
Then, in your _form partial you can let rails take care of the action like so:
<%= semantic_form_for(["admin", #team]) do |f| %>
.... #rest of the code
<% end %>

Ruby on Rails form_for causing path error

In my Ruby on Rails code, I have the following edit.html.erb file for tasks:
<%= render 'form' %>
I then have a _form template in the same directory with the following code:
<%= form_for #task do |f| %>
<%= fl.label :title %><br />
<% end %>
The problem is that I am getting an error when trying to navigate to the edit page. The error says "undefined task_path", so from what I can tell Rails is not properly identifying the path to my task.
The way the program is structured is that I have a List with many tasks, and each task has a list. The routes file declares the structure in this way:
resources :lists do
resources :tasks
end
How do I get the form_for to identify that I am trying to edit a task at /lists/:list_id/tasks/:task_id/edit?
Thank you for your help!
You are using Nested Resources the proper way to use that in a form is specifying the parent.
<%= form_for [#list, #task] do |f| %>
<%= f.label :title %><br />
<% end %>

Resources