【发布时间】:2014-09-28 11:16:20
【问题描述】:
我有一个关联工作和客户的 Rails 应用。一个客户有_许多工作和一个工作属于一个客户。
在我的客户展示页面上,有一个创建新工作的链接:
<%= link_to "Add New Job", new_customer_job_path(@customer) %>
点击该链接后,他们将被发送到新工作的新表单页面。提交表单后,请求会被推送到作业控制器,如下所示:
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy]
def index
@jobs = Job.all
end
def show
end
def new
@customer = Customer.find(params[:customer_id])
@job = @customer.jobs.build
end
def edit
end
def create
@job = Job.new(job_params)
respond_to do |format|
if @job.save
format.html { redirect_to customer_path(@customer), notice: 'Job was successfully created.' }
format.json { render action: 'show', status: :created, location: @job }
else
format.html { render action: 'new' }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to @job, notice: 'Job was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
def destroy
@job.destroy
respond_to do |format|
format.html { redirect_to jobs_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_job
@job = Job.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_params
params.require(:job).permit(:box_count, :install_date)
end
end
当控制器在表单提交后尝试重定向时收到以下错误:
No route matches {:id=>nil} missing required keys: [:id]
这是错误提示的行:
format.html { redirect_to customer_path(@customer), notice: 'Job was successfully created.' }
我可以看到参数中传递的 ID,但由于某种原因它不喜欢 customer_path(@customer)。
这是我的新工作表:
<%= form_for([@customer, @job]) do |f| %>
<% if @job.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@job.errors.count, "error") %> prohibited this job from being saved:</h2>
<ul>
<% @job.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :box_count %><br>
<%= f.number_field :box_count %>
</div>
<div class="field">
<%= f.label :install_date %><br>
<%= f.text_field :install_date %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
有人知道我做错了什么吗?
【问题讨论】:
-
你能粘贴你的控制器代码吗
-
我们需要查看您的表单代码,但它可能与 stackoverflow.com/questions/2034700/… 重复
-
@derekyau 已添加 - 抱歉,如果这是一个简单的问题,我不想弄乱它。
-
@robbrit 添加了表单代码,不要认为这是您引用的问题的重复,我刚刚完成了那个确切的问题。这是在后端 - 提交表单时会遇到错误,因为缺少 id。
-
@customer 未在此行中初始化:format.html { redirect_to customer_path(@customer), notice: '作业已成功创建。' }。该操作甚至在此行之前都没有提及。
标签: ruby-on-rails routes controllers