form for nested resource

泄露秘密 提交于 2019-12-12 08:45:12

问题


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.


回答1:


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



回答2:


This is how I solved mine :)

In your questions/_form.html.erb

<%= form_for [@job, @question] do %>

For this to work, you need the job's id. You'll pass it as follows: In the questions_controller.rb

def new
  @job = Job.find(params[job_id])
  @question = @job.questions.build
end

Build(.build) is similar to using new(.new) in the code above, with differences only in older versions of rails; rails 2 down.

Now for the create action (still in questions_controller.rb)

def create
  @job = Job.find(params[:job_id])
  @question = @job.questions.build(question_params)
end

If you only use these, the job_id and user_id field in the question model will be empty. To add the ids, do this: In your questions_controller.rb add job_id to job_params like so:

def question_params
  params.require(:question).permit(:ahaa, :ohoo, :job_id)
end

Then to pass the user's id (if you are using Devise), do:

def create
  @job = Job.find(params[:job_id])
  @question = @job.questions.build(question_params)
  @question.user_id = current_user.id
end


来源:https://stackoverflow.com/questions/6393464/form-for-nested-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!