form for nested resource

不问归期 提交于 2019-12-04 05:09:52
d11wtq

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

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