I am attempting to create a login system. My UserController has this to control the new action:
def new
#user = User.new
respond_to do |format|
format.json { render :json => #user }
format.html
end
end
and my routes.rb has this to link:
resources :user
The View's form to create a new user is this:
<%= form_for #user do |f| %>
however, I receive an Action Controller error with this:
undefined method `users_path' for #<#<Class
What has baffled me is why it is using users_path. This is a plural reference to my route. Why is it returning a plural error of user_path?? When I route `resources :users' it clears the error, but of course I don't have anything setup for that resource and thus produces other errors.
Inside form_for it creates an appropriate action and method based on whether or not the model is persisted.
If a model is unpersisted it will create an action of :new and method of :post. If it is persisted then it will be :update and :put instead.
For :new the default url is '/users' and for :edit it's '/users/:id'.
The fix is as Jim said. (Beat me to it.) Apply a url option to form_for.
resources :users is actually the correct structure, since it is a collection of users, not a single user. The route construction also expects a plural path (IIRC, it expects a plural path unless it finds a resource, as opposed to resources route), hence the attempt to use users_path.
Passing an explicit url parameter is another option <%= form_for #user, :url => user_path do |f| %>, since you already have things expecting singular routes
Related
Let's say i have a form which is at:
/categories/new
When form input is invalid I call render. Classic example:
def create
#category = Category.new(category_params)
if #category.save
flash[:success] = 'Category successfully created.'
redirect_to #category
else
render 'new'
end
end
My question is, why site path after call to render is just:
/categories
and not:
/categories/new
As I understand 'new' form should be rendered on the same page and those two paths clearly aren't the same.
As commenters suggested here is additional info:
related routes:
resources :categories do
resources :topics, name_prefix: 'category_',
except: [:index, :show, :edit, :update, :destroy]
end
category new action:
def new
#category = Category.new
end
Don't confuse what the url shows with what is actually rendered.
Short Answer
When you initially input your form you are actually doing a POST to /categories. This of course maps to the create action in your controller which when failing validation causes the new form to render - it isn't a redirect so the url won't change - the url remains the same as it did when you entered the action.
Detailed Explanation
When you invoke /categories/new you are actually being routed to the new action on the categories controller.
Your new action then sets any instance variables, for example #category, and rails will render the new.html.erb which contains your new category form.
When you submit the form it actually is doing a http POST to /categories, which routes to the create action of your categories controller. That url and http method is a result of what is generated from the form_for helper:
<%= form_for #category do |f| %>
This is why the url changes from /categories/new to /categories
Now the create action if it fails the validation simply renders the new form - it is not redirecting anywhere - the url remains unchanged from what it was when it entered this action - meaning, it remains as /categories.
Don't confuse the change in url with a redirection it's just that the form is posting to a different url than /categories/new, and the change in url is actually just a cosmetic issue.
Now if it is a concern to you, you can change the routing to something like the following:
resources :categories, except: [:create, :new]
post 'new_category' => 'categories#create'
get 'new_category' => 'categories#new'
This is mapping the POST and GET http methods to /new_category so the url appears the same for the new and create action invocations. Note you do need to change the url in the form_for helper to use this new route:
<%= form_for #category, url: 'new_category' do |f| %>
The custom routing:
resources :blog, controller: 'posts'
How do I rewrite this line <%= simple_form_for(#post, blog_path) do |f| %> to get rid of the below error?
TypeError in Posts#edit
ActionView::Template::Error (no implicit conversion of Symbol into Integer)
I also tried <%= simple_form_for(blog_path(#post)) do |f| %>, which gets rid of the error, but then if I want to edit the form the inputs are emptied of their saved data.
posts_controller
def new
#post = Post.new
respond_with(#post)
end
def edit
end
def create
#post = Post.new(post_params)
if current_user.admin
#post.save
respond_with(#post)
else
flash[:success] = 'Get out of here.'
redirect_to root_url
end
end
It can take a hash options, including url, so something like this:
Edit: changed blog_path to blogs_path. The blog_path is the show action, not the create action and therefore requires an id (and isn't a post path anyway). Try it out this way.
<%= simple_form_for(#post, url: blogs_path) do |f| %>
Don't know if this applies, but a really cool feature I found the other day was .becomes - where you can change the "class" of your object so that Rails treats it in a different way:
This can be used along with record identification in Action Pack to allow, say, Client < Company to do something like render partial: #client.becomes(Company) to render that instance using the companies/company partial instead of clients/client.
So...
If you had a Blog model, and wanted each #post to be treated as such (again, I don't know if this is your setup at all), you could do the following:
<%= simple_form_for #post.becomes(Blog) do |f| %>
I'll delete if inappropriate; it's come in handy quite a lot for me.
Update
If you'd like your posts_path to be blog (IE url.com/blog/1), you'll want to look at using the path option for the routes generator:
#config/routes.rb
resources :posts, path: "blog", as: :blog # -> url.com/blogs/2
I have a resource called Books. It's listed as a resource properly in my routes file.
I have a new action, which gives the new view the standard:
#book = Book.new
On the model, there are some attributes which are validated by presence, so if a save action fails, errors will be generated.
In my controller:
#book = Book.create
... # some logic
if #book.save
redirect_to(#book)
else
render :new
end
This is pretty standard; and the rationale for using render:new is so that the object is passed back to the view and errors can be reported, form entries re-filled, etc.
This works, except every time I'm sent back to the form (via render :new), my errors show up, but my URL is the INDEX URL, which is
/books
Rather than
/books/new
Which is where I started out in the first place. I have seen several others posts about this problem, but no answers. At a minimum, one would assume it would land you at /books/create, which I also have a view file for (identical to new in this case).
I can do this:
# if the book isn't saved then
flash[:error] = "Errors!"
redirect_to new_book_path
But then the #book data is lost, along with the error messages, which is the entire point of having the form and the actions, etc.
Why is render :new landing me at /books, my index action, when normally that URL calls the INDEX method, which lists all the books?
It actually is sending you to the create path. It's in the create action, the path for which is /books, using HTTP method POST. This looks the same as the index path /books, but the index path is using HTTP method GET. The rails routing code takes the method into account when determining which action to call. After validation fails, you're still in the create action, but you're rendering the new view. It's a bit confusing, but a line like render :new doesn't actually invoke the new action at all; it's still running the create action and it tells Rails to render the new view.
I just started with the Rails-Tutorial and had the same problem.
The solution is just simple: If you want the same URL after submitting a form (with errors), just combine the new and create action in one action.
Here is the part of my code, which makes this possible (hope it helps someone^^)
routes.rb (Adding the post-route for new-action):
...
resources :books
post "books/new"
...
Controller:
...
def create
#book = Book.new(book_params)
if #book.save
# save was successful
print "Book saved!"
else
# If we have errors render the form again
render 'new'
end
end
def new
if book_params
# If data submitted already by the form we call the create method
create
return
end
#book = Book.new
render 'new' # call it explicit
end
private
def book_params
if params[:book].nil? || params[:book].empty?
return false
else
return params.require(:book).permit(:title, :isbn, :price)
end
end
new.html.erb:
<%= form_for #book, :url => {:action => :new} do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :isbn %>
<%= f.text_field :isbn %>
<%= f.label :price %>
<%= f.password_field :price %>
<%= f.submit "Save book" %>
<% end %>
Just had the very same question, so maybe this might help somebody someday. You basically have to make 3 adjustments in order for this thing to work, although my solution is still not ideal.
1) In the create action:
if #book.save
redirect_to(#book)
else
flash[:book] = #book
redirect_to new_book_path
end
2) In the new action:
#book = flash[:book] ? Book.new(flash[:book]): Book.new
3) Wherever you parse the flash hash, be sure to filter out flash[:book].
--> correct URL is displayed, Form data is preserved. Still, I somehow don't like putting the user object into the flash hash, I don't think that's it's purpose. Does anyboy know a better place to put it in?
It doesn't land you at /books/new since you are creating resource by posting to /books/. When your create fails it is just rendering the new action, not redirecting you to the new action. As #MrYoshiji says above you can try redirecting it to the new action, but this is really inefficient as you would be creating another HTTP request and round trip to the server, only to change the url. At that point if it matters you could probably use javascript change it.
It can be fixed by using same url but different methods for new and create action.
In the routes file following code can be used.
resources :books do
get :common_path_string, on: :collection, action: :new
post :common_path_string, on: :collection, action: :create
end
Now you new page will render at url
books/common_path_string
In case any errors comes after validation, still the url will be same.
Also in the form instead using
books_path
use
url: common_path_string_books_path, method: :post
Choose common_path_string of your liking.
If client side validation fails you can still have all the field inputs when the new view is rendered. Along with server side errors output to the client. On re-submission it will still run create action.
In books_controller.rb
def new
#book = current_user.books.build
end
def create
# you will need to have book_params in private
#book = current_user.books.build(book_params)
if #book.save
redirect_to edit_book_path(#book), notice: "Book has been added successfully"
# render edit but you can redirect to dashboard path or root path
else
redirect_to request.referrer, flash: { error: #book.errors.full_messages.join(", ") }
end
end
In new.html.erb
<%= form_for #book, html: {class: 'some-class'} do |f| %>
...
# Book fields
# Can also customize client side validation by adding novalidate:true,
# and make your own JS validations with error outputs for each field.
# In the form or use browser default validation.
<% end %>
I have a polymorphic nested resource for user
companies/:id/users/new
departments/:id/users/new
Now, if the create action succeeds I can redirect to proper path (I redirect back to new) but if it fails how do I render the same page again as I need to display errors and let the filled in values as is. 'render action: new' defaults to companies/:id/users/new
if #user.save
redirect_to send("new_#{#parent.class.to_s.underscore}_user_path", #parent
else
render action: new
You can try make routes through values
redirect_to [:new, #parent, :user]
Nevermind, if it helps someone, it turns out in my nested form I had used #company, #user instead of #parent, #user. It should have been
form_for [#parent, #user] do |f|
Now it works fine. Thanks for all answers.
I have the following route in my rails application
match '/settings', to: 'Users#edit', as: 'settings'
And corresponding controller code
def edit
#user = current_user
end
def update
correct_user
#user = User.find(params[:id])
if !#user.authenticate(params[:old_password])
flash[:error] = 'Old password did not match'
redirect_to settings_path
elsif #user.update_attributes(params[:user])
flash[:success] = "Settings updated"
redirect_to settings_path
else
render 'edit'
end
end
My edit page is as of now just a password change page, and when I visit /settings I see the page I'd except. When I redirect_to settings_path, the url remains /settings, which is the behavior I want.
In my edit template, I have code to handle object errors and render them on the page. When render 'edit, this code is triggered if there was an object error. If I redirect to the page, however, the code is not there. So I need to call render 'edit' to see the errors.
However, calling render 'edit' causes the URL to change to /users/:id/edit, which is exactly what I don't want. I'd like the URL to remain /settings after calling render 'edit'. How can I achieve this?
NOTE: I've already searched SO and other parts of the internet but have found nothing that suits my needs. There are one or two SO topics with similar issues but they all use flashing and hacky redirect-based workarounds, which is not what I want.
You would want to set up your routes like this:
match 'settings': 'users#edit', via: :get
match 'settings': 'users#update', via: :put
Then the form should be declared like this:
<%= form_for #user, url: settings_path %>
In your controller, make sure you're calling render like this:
render action: "edit"
You probably have a bad link_to in your view, one using the old-style :controller and :action arguments separately instead of using settings_path.
Keep in mind that if there are two routes to the same controller and action pair, the first route defined has priority. Define your custom route first to ensure it's used by default.