views:

2580

answers:

2

Hello, I'm new to ruby and started to create my *nd toy app. I:

  1. Created controller 'questions'
  2. Created model 'question'
  3. Created controller action 'new'
  4. Added 'New.html.erb' file

in erb file I use form_for helper and and new controller action where I instantiate @question instance variable. When I try to run this I get 'undefined method: questions_path for #<ActionView::Base:0x5be5e24>' error. Below is my new.html.erb:

<%form_for @question do |f| %>
   <%=f.text_field :title %>
<%end%>

Please advise how to fix this and also help me with aliasing this controller action. What I mean is I would like to type http://mysite/questions/ask, instead of /questions/create Thanks, Valve.

+4  A: 

In config/routes.rb you will need to add:

map.resources :questions

to fix the undefined method questions_path problem.

One way to get /questions/ask is to modify routes.rb like so:

map.ask_question '/questions/ask', :controller => 'questions', :action => 'create'

which will give you ask_question_path which you can reference in your code.

Michael Sepcot
A: 

It looks like you did all of these steps individually. You should try out the scaffold generator, which will build all of this for you.

Example:

>ruby script/generate scaffold question question:string answer:string votes:integer
  exists  app/models/
  exists  app/controllers/
  exists  app/helpers/
  create  app/views/questions
  exists  app/views/layouts/
  exists  test/functional/
  exists  test/unit/
  exists  public/stylesheets/
  create  app/views/questions/index.html.erb
  create  app/views/questions/show.html.erb
  create  app/views/questions/new.html.erb
  create  app/views/questions/edit.html.erb
  create  app/views/layouts/questions.html.erb
  create  public/stylesheets/scaffold.css
  create  app/controllers/questions_controller.rb
  create  test/functional/questions_controller_test.rb
  create  app/helpers/questions_helper.rb
  route  map.resources :questions
  dependency  model
  exists    app/models/
  exists    test/unit/
  exists    test/fixtures/
  create    app/models/question.rb
  create    test/unit/question_test.rb
  create    test/fixtures/questions.yml
  create    db/migrate
  create    db/migrate/20081201150131_create_questions.rb

So as you can see, with a scaffold we get our model, our controller, our views, our route, a database migration that will build a Questions table with two fields, and RESTful controller actions to immediately add/update/view/delete any question data. Oh, and most importantly, an empty set of test files ready for your tests to be written :).

mwilliams
hi, thanks for quick response. I opted for manual way because I wanted to 'grok' the inner steps the scaffolding performs, and of course, stuck :-)
Valentin Vasiliev