我有一个用户可以添加数据的表,我还包含一个用户删除一行数据的按钮:
<tbody>
<% @jobs.each do |job| %>
<tr>
<td><%= link_to job.job_title, job.url, :target => "_blank" %></td>
<td><%= job.company %></td>
<td><%= job.location %></td>
<td><%= link_to "", list_url(job), method: :delete, class: "fa fa-trash-o" %></td>
</tr>
<% end %>
</tbody>
然而,当按下删除按钮时,我得到一个“未定义的方法`destroy for nil:NilClass”错误。在我的服务器日志中,它表示ID为null,我似乎无法获取该特定数据行的id。
我已经查看了其他类似的Stackoverflow问题,但我找到的解决方案对我来说没有用。
此处参考的是与添加,显示和删除数据相关的路线:
get '/jobs' => 'search#list', as: 'list'
post '/jobs' => 'search#create'
delete '/jobs' => 'search#destroy'
我的控制员:
def new
@job = Job.new
end
def create
@job = Job.new(job_params)
if @job.save
redirect_to list_url, notice: "You've successfully added the job to the list"
else
render 'search', notice: "Something went wrong, please try again"
end
end
def list
@jobs = Job.all
@job = Job.find_by_id(params[:id])
end
def destroy
@job = Job.find_by_id(params[:id])
@job.destroy
redirect_to list_url, notice: "Job destroyed"
end
def job_params
params.require(:job).permit(:job_title, :company, :location, :url)
end
答案 0 :(得分:0)
在删除链接中,您希望链接到对象本身,而不是对象的URL。所以改变
<td><%= link_to "", list_url(job), method: :delete, class: "fa fa-trash-o" %></td>
到
<td><%= link_to "", job, method: :delete, class: "fa fa-trash-o" %></td>
最重要的是,您需要定义相应的CRUD
路由,因此我建议在routes.rb
文件中添加以下内容:
resources :jobs, controller: 'search'
答案 1 :(得分:0)
如果您尝试指定特定的工作实例,请不要认为您想要链接到list_url
。也许像是
<td><%= link_to "", job_path(job), method: :delete, class: "fa fa-trash-o" %></td>