Undefined method *_path when trying to use form_for - ruby-on-rails

Category controller:
def new
#cat = Category.new
respond_to do |format|
format.html
end
end
View:
%p Add new category:
~form_for(#cat) do |f|
%div.field
~f.label :name
~f.text_field :name
%div.field
~f.label :description
~f.text_area :description
%div.field
~f.submit
Routes:
resources :category
When I try to load category/new in the browser I get:
undefined method `categories_path' for #<#<Class:0x10d9c9ee8>:0x10d9b0768>
Extracted source (around line #3):
1: %h1 Category#new
2: %p Add new category:
3: ~form_for(#cat) do |f|
4: %div.field
5: ~f.label :name
Any ideas why my form isn't showing?
Also, on my category/index page, where I want to show all categories, under the list of categories I'm getting #<Category:0x10d736b40>. Can I get rid of that somehow?

The route should be
resources :categories
not
resources :category

A bit long for a comment so I've added the following as an answer instead.
If you want a singular resource you need to do:
resource :category
Which will generate only 6 routes (no index):
GET /category/new new
POST /category create
GET /category show
GET /category/edit edit
PUT /category update
DELETE /category destroy
But your controller will still be plural, unless you do the following:
resource :category, controller: :category

Related

Form_for is giving me a No Method Error when trying to create a new object

So as it stands I have a form partial which starts off as:
<%= form_for(#merchandise) do |f| %>
It works perfectly for editing the data that I have already assigned in the rails console. When I try to use it for a "new" form that creates new merchandise (in this case the singular form of merchandise, I don't have nested resources, multiple models etc.), I get a no Method error that states
"undefined method 'merchandises_path' for #<#<Class:0x64eaef0>:0x95d2370>".
When I explicitly state the URL in the form_for method:
<%= form_for(#merchandise url:new_merchandise_path) do |f| %>
I get it to open and I finally have access to the form, however in this case I get a routing error that states
"No route matches [POST] "merchandise/new"".
I decided to write out that route in my routes file which previously just had:
root "merchandise#index" resources :merchandise
After I add the route it literally does nothing. I click submit and it takes me to the form but there is no new data in the database. I am at a complete loss and have been at this for hours googling and stack overflowing and I just don't know what to do anymore. All help is seriously appreciated. I'm adding a pastebin with all my code in the following url:
http://pastebin.com/HDJdTMDt
I have two options for you to fix it:
Option 1:
Please try to do this for best practice in Rails:
routes.rb
change your routes use plural
resources :merchandises
merchandises_controller.rb
Rename your file controller and class into MerchandisesController
class MerchandisesController < ApplicationController
def index
#merchandise = Merchandise.all
end
def new
#merchandise = Merchandise.new
end
def create
#merchandise = Merchandise.new(merchandise_params)
if #merchandise.save
redirect_to merchandises_path
else
render :new
end
end
def show
#merchandise = Merchandise.find(params[:id])
end
def edit
#merchandise = Merchandise.find(params[:id])
end
def update
#merchandise = Merchandise.find(params[:id])
if #merchandise.update(merchandise_params)
redirect_to #merchandise, notice: "The movie was updated"
else
render :edit
end
end
def merchandise_params
params.require(:merchandise).permit(:shipper, :cosignee, :country_arrival_date, :warehouse_arrival_date, :carrier, :tracking_number, :pieces, :palets, :width, :height, :length, :weight, :description, :cargo_location, :tally_number, :customs_ref_number, :released_date, :updated_by, :country_shipped_to, :country_shipped_from)
end
end
Option 2:
If you want to not change many code
/merchandise/_form.html.erb
in partial file
/merchandise/new.html.erb
<%= render 'form', url: merchandise_path, method: 'post' %>
/merchandise/edit.html.erb
<%= render 'form', url: category_path(#merchendise.id), method: 'put' %>

simple_form undefined method model_name 3 classes error

So I just Nested some resources that weren't Nested before and since I have been trying to fix all of the path references. The biggest issue I have been having is with the fact that there are 2 nested resources within a larger nested resource like so:
Users->Photos->Comments
On my form, it keeps giving me the following error
undefined method `model_name' for "/users/2/photos/2/comments/new":String
The error page says that the source is around line #1 of the following (my comments/_form partial):
= simple_form_for ([#comment, new_user_photo_comment_path(#user,#photos,#comment)]) do |f|
= f.input :content, label: "Reply to thread"
=f.button :submit, class: "button"
This is my Comments controller:
class CommentsController < ApplicationController
before_action :authenticate_user!
def new
#photo=Photo.find(params[:photo_id])
end
def create
#photo =Photo.find(params[:photo_id])
#comment=Comment.create(params[:comment].permit(:content, :id, :photo_id))
#comment.user_id= current_user.id
#comment.photo_id= #photo.id
#user= User.find_by(params[:id])
if #comment.save
redirect_to user_photo_path(#photo, #user)
else
render 'comments/new'
end
end
end
At first, it is not preferably to nest resources deeper than two times.
You should consider to nest comments within only photos. It`s ok to do like so in routes.rb:
resources :users do
resources :photos
end
resources :photos do
resources :comments
end
And you errors is because
= simple_form_for ([#comment, new_user_photo_comment_path(#user,#photos,#comment)]) do |f|
gives for method simple_form_for as parameters:
1 - model Comment
2 - String /users/2/photos/2/comments/new
to set proper path (form action) form builders need models as all arguments.
Maybe something like
= simple_form_for ([#user,#photos,#comment]) do |f|
should work

Rails: How to hard code field in a form_for

I am working on a Rails project that has nested resources as defined below.
resources :projects do
resources :entries
end
For the entries#new form, I would like to hard code the project_id from the path projects/project_id/entries/new as the project_id field of form_for in the entries' views directory. When I write:
= f.label :project_id
%br
= f.select :project_id, #project
I get the following error:
undefined method `empty?' for #<Project:0x007fa9adc06120>
Any ideas how to send the #project as that field to the form without getting f.select errors? I believe f.select takes a colleciton and so it doesn't like me just giving it a single object as its second parameter.
Thanks for your help!
I guess you have your #entry in the new method of your controller, something like this:
def new
#entry = Entry.new
# etc.
You can use this instead:
def new
#entry = #project.entries.build
# it will set project_id to the #project.id
and in the view:
= f.hidden_field :project_id
If you don't want to initialize with the project_id directly in the view:
= f.hidden_field :project_id, value: #project.id

NoMethodError when going to page to create new record

I keep struggling with this sort of thing in Rails. I'm trying to create a statistics record for a given city. I guess I don't need to paste my models? Below is the error, URL, view and controller code.
Here's my error:
NoMethodError in Statistics#new
Showing new.html.haml where line #2 raised:
undefined method `statistics_path' for #<#<Class:0x007faf5e172928>:0x007faf5e717ef0>
The path I go to is:
http://127.0.0.1:3000/cities/1/statistics/new
Routes:
city_statistics GET /cities/:city_id/statistics(.:format) statistics#index
POST /cities/:city_id/statistics(.:format) statistics#create
new_city_statistic GET /cities/:city_id/statistics/new(.:format) statistics#new
edit_city_statistic GET /cities/:city_id/statistics/:id/edit(.:format) statistics#edit
city_statistic GET /cities/:city_id/statistics/:id(.:format) statistics#show
PUT /cities/:city_id/statistics/:id(.:format) statistics#update
DELETE /cities/:city_id/statistics/:id(.:format) statistics#destroy
cities GET /cities(.:format) cities#index
POST /cities(.:format) cities#create
new_city GET /cities/new(.:format) cities#new
edit_city GET /cities/:id/edit(.:format) cities#edit
city GET /cities/:id(.:format) cities#show
PUT /cities/:id(.:format) cities#update
DELETE /cities/:id(.:format) cities#destroy
routes.rb:
resources :cities do
resources :statistics
end
routes.rb:
Controller:
def new
#statistic = Statistic.new
respond_to do |format|
format.html # new.html.haml
format.json { render :json => #statistic }
end
end
View:
%legend New Stat
= form_for(#statistic) do |f| ###### ERROR HERE #######
= f.label :city_id
= f.text_field :city_id
.actions
= f.submit "Add", :id => "add-statistic", :class => "btn btn-primary"
EDIT added routes.rb
Two things.
As #nathan points plural form of city in English is cities so there's something wrong with your routes, maybe you renamed it? (please include routes.rb)
You have a route for statictic which is a nested resource of city, so for form helper you shoud pass
= form_for([#city, #statistic]) do |f|
Youre path file shows citys instead of cities. Perhaps you were bitten by an ActiveResource pluralize problem?

form for nested resource

I have gone through tons of the form_for nested resource questions and can't get any of the solutions to work for me. I figured its time to ask a personalized question.
I have two models, jobs and questions, jobs has_many questions and questions belong_to jobs.
I used scaffolding to create the controllers and models then nested the resources in the routes.rb.
root :to => "pages#home"
resources :jobs do
resources :questions
end
get "pages/home"
get "pages/about"
get "pages/contact"
class Job < ActiveRecord::Base
has_many :questions
end
class Question < ActiveRecord::Base
belongs_to :job
end
Right now I am trying to access '/jobs/1/questions/new' and keep getting the
NoMethodError in Questions#new
I started with the error No route matches {:controller=>"questions"} when the code was
<%= form_for(#question) do |f| %>
I know this is wrong, so I started to try other combos and none of them worked.
I've tried
<%= form_for([#job.questions.build ]) do |f| %>
that
<%= form_for([#job, #job.questions.build ]) do |f| %>
that
<%= form_for(#job, #question) do |f| %>
Among a bunch of other combinations and that are not working.
Here is a link to my rake routes : git clone https://gist.github.com/1032734
Any help is appreciated and let me know if you need more info, thanks.
I just pass the URL as an extra option:
<%= form_for(#question, :url => job_questions_path(#job)) do %>
EDIT:
Also try:
form_for([#job, #question])
This is how I solved mine :)
In your questions/_form.html.erb
<%= form_for [#job, #question] do %>
For this to work, you need the job's id. You'll pass it as follows:
In the questions_controller.rb
def new
#job = Job.find(params[job_id])
#question = #job.questions.build
end
Build(.build) is similar to using new(.new) in the code above, with differences only in older versions of rails; rails 2 down.
Now for the create action (still in questions_controller.rb)
def create
#job = Job.find(params[:job_id])
#question = #job.questions.build(question_params)
end
If you only use these, the job_id and user_id field in the question model will be empty. To add the ids, do this:
In your questions_controller.rb add job_id to job_params like so:
def question_params
params.require(:question).permit(:ahaa, :ohoo, :job_id)
end
Then to pass the user's id (if you are using Devise), do:
def create
#job = Job.find(params[:job_id])
#question = #job.questions.build(question_params)
#question.user_id = current_user.id
end

Resources