Ruby on rails 在Rails中按ID路由返回
我有一个rails应用程序,其中包含相关的作业和客户。一个客户有很多工作,一个工作属于一个客户 在“我的客户展示”页面上,有一个创建新工单的链接:Ruby on rails 在Rails中按ID路由返回,ruby-on-rails,routes,controllers,Ruby On Rails,Routes,Controllers,我有一个rails应用程序,其中包含相关的作业和客户。一个客户有很多工作,一个工作属于一个客户 在“我的客户展示”页面上,有一个创建新工单的链接: <%= link_to "Add New Job", new_customer_job_path(@customer) %> 以下是错误调用的行: format.html { redirect_to customer_path(@customer), notice: 'Job was successfully created.' }
<%= link_to "Add New Job", new_customer_job_path(@customer) %>
以下是错误调用的行:
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 %>
禁止保存此作业:
有人知道我做错了什么吗 @客户从未初始化。 试试这个:
def create
@job = Job.new(job_params)
respond_to do |format|
if @job.save
@customer = @job.customer
format.html { redirect_to customer_path(@customer), notice: 'Job was successfully created.' }
...
此外,您的作业参数必须允许客户id:
def job_params
params.require(:job).permit(:box_count, :install_date)
params.permit(:customer_id)
end
你能粘贴你的控制器代码吗?我们需要查看你的表单代码,但它可能与添加的@derekyau重复-抱歉,如果这是一个简单的问题,我不想把它弄得一团糟。@robbrit添加了表单代码,不要认为这与你引用的问题重复,我刚刚解决了这个问题。这是在后端-提交表单时,由于缺少id,表单在保存时遇到错误。@此行中未初始化customer:format.html{redirect_to customer_path(@customer),注意:“作业已成功创建”。}。该操作甚至没有在这一行之前提到它。逻辑是有道理的,但同样的错误:没有路由匹配{:id=>nil}缺少必需的键:[:id]Ah,在job_参数中,您还需要允许customer_id。我需要将id传递到新表单上的表单字段中以将其添加到DB吗?如果它说它是nil,那么也许这就是问题所在?我在create块中添加了它,它起了作用:@customer=customer.find(params[:customer_id]),让我们来看看。
def create
@job = Job.new(job_params)
respond_to do |format|
if @job.save
@customer = @job.customer
format.html { redirect_to customer_path(@customer), notice: 'Job was successfully created.' }
...
def job_params
params.require(:job).permit(:box_count, :install_date)
params.permit(:customer_id)
end