Rails Tutorial NoMethodError in Users#index - ruby-on-rails

I'm following along with the Rails tutorial by Michael Hartl. We just created a Users database (this first part of "demo_app"), but when I start the server and navigate to the new users page I get the following error:
NoMethodError in Users#index
and the application trace:
app/views/layouts/application.html.erb:5:in `_app_views_layouts_application_html_erb__2922823401409246272_70101530338460'
app/controllers/users_controller.rb:7:in `index'
I really have no idea how to decipher these error messages but here is my users_controller file:
class UsersController < ApplicationController
# GET /users
# GET /users.json
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end
....
....
Line 7 is the respond_to do |format| line. Any thoughts? Complete newbie to Ruby and Rails (figured I'd learn Ruby on the fly).
P.s. it's not a syntax error. I know that much.

Haven't you forgot one end?
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end

I believe your problem is in not closing out the respond_to do |format| block. Should be:
def index
#users = User.all
respond_to do |format|
format.html #index.html.erb
format.json { render json: #users }
end
end

I tried to compare your code with mine, but I am not sure where you are in the tut. In chapter 2, we built a demo app, but in my Users.controller there is no 'respond_to … block.
In that case, you should probably close the def index with end, but I am not sure where your respond_to block should go in that case.
In chapter 4, where there IS a respond_to block, I don't have an index-method in my Users.controller
So, could you tell what chapter you are working in? And maybe post the complete Users.controller file?

Does your config/routes.rb file contain a line declaring that your urls /users/* should dispatch to your UsersController?
If the line doesn't exist, you should add in config/routes.rb
resources :users

Related

ActionController::UnknownFormat in CoinsController#index

In my CoinsController, I have added a respond_to method in my index controller. I'm not sure if my code is right but here is my index controller below:
def index
paginated = paginate(Coin.recent)
render_collection(paginated)
respond_to do |format|
format.json do
format.html # index.html.erb
format.json { render json: render_collection(paginated) }
end
end
end
I read the few documents I found online about respond_to do |format| method and when I tried adding it manually the way it is in the documentation, I get an Unknown Format error. What I'm trying to do is have logic that handles both html and json, so that it can act as a json api and a view renderer.
Any ideas?
Ok guys so I found out the solution to my problem:
def index
paginated = paginate(Coin.recent)
# render_collection(paginated)
respond_to do |format|
format.json do
render_collection(paginated)
end
format.html do
render :index
end
end
end
I had commented out the render_collection(paginated) and then added json and html to it's own block and it worked.

Rails 5 is ignoring view templates

In my Rails project, I ran:
rails generate scaffold car
which successfully created all of the necessary files and directories for the application. This includes the standard application.html.erb layout file, as well as the app/views/cars directory that includes more standard html.erb files (index, show, ETC.)
In addition, my cars route is in place in config/routes.rb.
My next command is rails server, which is also successful.
When I open my browser and go to localhost:3000, the welcome page for ruby on rails pops up as normal. I'm expecting that when I go to localhost:3000/cars, I'll see the html rendered from app/views/cars/index.html.erb. If not, I at least expect that it will default to application.html.erb.
Instead, I am repeatedly receiving the following:
>ActionController::UnknownFormat in CarsController#index
>CarsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []
My controller class looks like this:
class CarsController < ApplicationController
before_action :set_car, only: [:show, :edit, :update, :destroy]
# GET /cars
# GET /cars.json
def index
#cars = Car.all
end
# GET /cars/1
# GET /cars/1.json
def show
end
# GET /cars/new
def new
#car = Car.new
end
# GET /cars/1/edit
def edit
end
# POST /cars
# POST /cars.json
def create
#car = Car.new(car_params)
respond_to do |format|
if #car.save
format.html { redirect_to #car, notice: 'Car was successfully created.' }
format.json { render :show, status: :created, location: #car }
else
format.html { render :new }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cars/1
# PATCH/PUT /cars/1.json
def update
respond_to do |format|
if #car.update(car_params)
format.html { redirect_to #car, notice: 'Car was successfully updated.' }
format.json { render :show, status: :ok, location: #car }
else
format.html { render :edit }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cars/1
# DELETE /cars/1.json
def destroy
#car.destroy
respond_to do |format|
format.html { redirect_to cars_url, notice: 'Car was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_car
#car = Car.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def car_params
params.fetch(:car, {})
end
end
I'd greatly appreciate any insight into this issue. I've followed every bit of advice I've seen on the internet regarding layouts, controllers, and views, and I'm having no luck.
Thanks in advance!
Thanks to everyone who was trying to answer my question! It was a stumper, but I've discovered the problem:
After uninstalling and reinstalling rails a few times, I created a dummy rails project and generated a new scaffold "car." Upon running rails server and loading up localhost:3000/cars, the default layout was rendered as normal. Thinking that reinstalling rails had solved it, I then linked the dummy project to a remote github repository.
At this point, running rails server and loading localhost:3000/cars showed me the same error message as before. This made me believe that something about the remote repo was messing up my project, so I googled around for this error message and github.
I stumbled upon the following link which ultimately answered my question:
https://github.com/rails/rails/issues/18660
Turns out, one of the directories in my root path was capitalized, and that was throwing rails off right away. As soon as I renamed the capitalized directory to all lowercase, the app ran flawlessly.
I'm frustrated by ruby on rails' extremely opinionated conventions, and especially since this project is almost a week late due to such an esoteric mistake. But I'm over the moon to have it running smoothly now and I hope this may help someone else in the future.
Thanks again all!

what is (.:format) appended to url path during rake routes?

When I run rake routes, I get something like this:
signin /signin(.:format) application#signin
What is the (.:format) in the middle?
It's an optional format. It matches URLs like:
/signin
/signin.html
/signin.json
This format can then be used in the controller. For example:
class UsersController < ApplicationController
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render xml: #users}
format.json { render json: #users}
end
end
end
This code snippet is from Action Controller Overview. See more details in the routing guide.

Rails code generated with ORM mangomapper throws NoMethodError (undefined method `each' for "4d2aeaea4403baa84a000005":String)

I am absolutely totally news to Rails and to MongoDB. I have been following tutorials from a good book and create my first Rails app with a light Twitter copy. Everything went fine and smooth.
But as part of my learning process I wanted to build the same app using MongoDB rather than the default SGBD.
I therefore configured mongo and installed the mongo_mapper gem. Everything has been configured properly following this tutorial: http://www.mongodb.org/display/DOCS/Rails+3+-+Getting+Started. Then I struggled a little bit to allow Rails generate to work without throwing me the --orm not specified error. In order to get past this I had to add the rails3-generators gem and add it to the Gemfile.
Once all this was done, everything worked fine. I was able to successfully launch the Rails server.
I added a User controller thanks to the generate. The page works fine and even lists the users I have previously added:
However all the other actions, showing, editing, deleting, etc. are not working (creating works, but then it goes to show and the errors comes):
It's virtually the same error for all different actions.
The one difference I can notice right off the bat is that with the non MongoDB db, the id's of the user was starting at 1, etc. but here with MongoDB it looks like a randomly generated id that is much more complex and that is not of type int: 4d2ae91d4403baa84a000002
I am thinking that this may be creating the issues, since all action are using the id as a parameter... but I have no idea how to fix this. I have looked at the ruby generated code and it looks alright to me (extremely similar to the code generate for the default db).
Any help would be greatly appreciated ! I don't know how to go forward with my project without solving a simple generate code with mongodb.
Thanks,
Alex
ps:
please that I did not write any of this code at all. everything has been generated, which is kinda why I expected to work from the get go...
as asked here is the code for users_controllers:
class UsersController < ApplicationController
# GET /users
# GET /users.xml
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
# GET /users/1
# GET /users/1.xml
def show
#user = User.first(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
# GET /users/new
# GET /users/new.xml
def new
#user = User.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #user }
end
end
# GET /users/1/edit
def edit
#user = User.first(params[:id])
end
# POST /users
# POST /users.xml
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
format.html { redirect_to(#user, :notice => 'User was successfully created.') }
format.xml { render :xml => #user, :status => :created, :location => #user }
else
format.html { render :action => "new" }
format.xml { render :xml => #user.errors, :status => :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.xml
def update
#user = User.first(params[:id])
respond_to do |format|
if #user.update(params[:user])
format.html { redirect_to(#user, :notice => 'User was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #user.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.xml
def destroy
#user = User.first(params[:id])
#user.destroy
respond_to do |format|
format.html { redirect_to(users_url) }
format.xml { head :ok }
end
end
end
Hummm so it seems I found the pb...
I replaced:
#user = User.first(params[:id])
by
#user = User.find(params[:id])
But again, this code was generated... so where does the error come from ? Is there a "bug" in rails3-generators ? Or somehow I screwed up the generation ?
Alex

Add JSON support to Rails app

I am experimenting with Rails and was wondering what's needed to allow/add support for JSON requests?
I have a vanilla installation of Rails 2.3.5 and the default scaffolding seem to provide support for HTML & XML requests but not JSON.
class EventsController < ApplicationController
# GET /events
# GET /events.xml
def index
#events = Event.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #events }
end
end
# GET /events/1
# GET /events/1.xml
def show
#event = Event.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #event }
end
end
...
I'm new to this but it would appear as though i would need to add a format line in each method along the lines of:
format.js { render :js => #event.json }
couldn't this be done automatically? perhaps there's a template somewhere i need to update...or a flag i can set? Or perhaps, and most likely, I've missed the boat entirely?!?
You do:
format.json {render :json=>#event}
That will render the default activerecord JSON for the model
The option of ease of use is that you can write a private method which takes the format object and an object to render and then, based on the format, renders different things. Example:
class MyController<ApplicationController
def show
#event=Event.find(params[:id])
respond_to do {|format| myRenderer(format,#event)}
end
...
private
def myRenderer(fmt,obj)
fmt.json {render :json=>obj}
fmt.html
fmt.xml {render :xml=>obj}
end

Resources