GeekedOut
GeekedOut

Reputation: 17185

Ruby - writing a basic controller

I am trying to learn Ruby on Rails and trying to write some of the code by hand so that I learn how it works.

I made this tiny controller:

class TestsController < ApplicationController
  def test

      def show
        render :text => "Hi from TestsController!"
      end  

  end
end

and this is what is left of my view:

<h3> Hello test </h3>

and this is my routes.rb snippet:

resource :test

but it gives an error that: The action 'show' could not be found for TestsController

Thanks!

This is the output of rake routes:

home_index GET    /home/index(.:format) home#index
      root        /                     home#index
      test POST   /test(.:format)       tests#create
  new_test GET    /test/new(.:format)   tests#new
 edit_test GET    /test/edit(.:format)  tests#edit
           GET    /test(.:format)       tests#show
           PUT    /test(.:format)       tests#update
           DELETE /test(.:format)       tests#destroy

Upvotes: 2

Views: 266

Answers (3)

ericraio
ericraio

Reputation: 1469

What @klump said is correct. Try running a basic scaffold. This will generate a controller, model and views for you. This generator is great when you are learning rails.

 rails g scaffold Test

Also check out http://www.railsforzombies.com as it is a great way to learn rails.

Upvotes: 2

shime
shime

Reputation: 9008

You use respond_to when you want your action to respond to multiple formats. Client sets it's desired format in HTTP Accept header.

You can then specify different action for each format.

Example

def show
    respond_to do |format|
       format.html { Rails.logger.debug "rendering show.html" }
       format.xml { Rails.logger.debug "rendering show.xml" }
       format.js { Rails.logger.debug "rendering show.js" }
    end
end

Refer to the API for more examples.

Upvotes: 1

klump
klump

Reputation: 3269

A basic controller looks like this:

class TestsController < ApplicationController
  def show
  end
end

You do not need the respond_to block if you only want to render the default view (in this case: app/views/tests/show.html.erb). The respond_to block is when you have some more advanced needs.

Upvotes: 5

Related Questions