Search code examples
ruby-on-railsform-fornested-resources

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.


Solution

  • 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])