2015-03-30 69 views
0

我有一个链接,我想通过URL传递一个ID以在其他模型的操作(如新建和创建)中处理它。通过链接传递的URL无法在创建操作上处理

在_response.html.erb

<%= link_to "Reply", new_subcomment_path(:response_id => response.id), id: "new_subcomment"%> 

点击时,它会带给我新的观点,实际上我可以看到我通过上面的链接从_response.html.erb部分传递的参数。即:http://localhost:3000/subcomments/new?response_id=152完全没问题。

new.html.erb

<%= simple_form_for @subcomment do |f| %> 
<%= f.input :comment_text, as: :text, input_html: {rows: 1} %> 
<%= f.button :submit %> 

现在的问题是,当我点击提交后,我会得到这个错误:

ActiveRecord::RecordNotFound (Couldn't find Response without an ID): app/controllers/subcomments_controller.rb:10:in `create'

这里是我的subcomments_controller.rb

def new 
    @response = Response.find(params[:response_id]) 
    @subcomments = @response.subcomments.all 
    @subcomment = @response.subcomments.new 
end 

def create 
    @response = Response.find(params[:response_id]) 
    @task = @response.task 
    @subcomment = @response.subcomments.new(subcomment_params) 
    @subcomment.save 

    redirect_to @task 

end 

private 
def subcomment_params 
    params.require(:subcomment).permit(:comment_text) 
end 

这里是我的路线文件:

resources :tasks do 
    resources :responses 
end 
resources :responses do 
    resources :subcomments 
end 
resources :subcomments 

我真的很感兴趣的是,我所传递的链接和参数的错在哪里,因为它似乎无法在创建动作中处理。 请帮我弄清楚这里有什么错误>。 <

回答

0

你的形式不具有的response_id去任何地方,所以没有办法为它提交给创建行动,你simple_form_for内添加这样一行:

<%= f.hidden :response_id %> 

但请注意:做这个用户可以改变这个值,我认为这不是你和你的业务逻辑的问题,因为你已经接受response_id链接到你的new行动。

0

那么你的问题是在create行动的第一行:@response = Response.find(params[:response_id])。你正在努力寻找使用参数记录params[:response_id]但上述收益nil,因此错误Couldn't find Response without an ID

这是因为如果你正在做Respond.find(nil)。检查你的参数; respond_id可能不存在或以不同的方式嵌套。