简体   繁体   English

Rails路线参数查找表格

[英]rails routes params find for a form

I am having a bit of trouble with my rails application. 我的rails应用程序遇到了一些麻烦。 It short, its a social networking app where users have a profile, have submissions, and can comment on submissions. 简而言之,它是一个社交网络应用程序,用户可以在其中拥有个人资料,提交内容并可以对提交内容发表评论。

My routes are as follows: 我的路线如下:

map.connect '/:username', :controller => 'users', :action => 'show'  
map.connect '/:username/:id', :controller => 'submissions', :action => 'show'

So when they are viewing a submission the URL looks something like: 因此,当他们查看提交内容时,URL类似于:

http://www.example.com/users_username/2342 http://www.example.com/users_username/2342

The number is the id number of the category. 该数字是类别的ID号。 So far so good. 到现在为止还挺好。 Where I am running into trouble is when I try to submit a comment on the submission. 我遇到麻烦的地方是我尝试对提交的内容发表评论。 There is a form for submitting comments on each submission page that looks like this: 在每个提交页面上都有一个用于提交评论的表单,如下所示:

<% form_for Comment.new do |f| %>  
    <%= f.text_area :message %>  
    <%= f.submit "Submit", :disable_with => 'Submitting...' %>  
<% end %>  

and the controller looks like this: 控制器看起来像这样:

def create
    submission = Submission.find(params[:id])
    comment = cat.comments.create(params[:comment])
    comment.created_at = Time.now
    comment.save
    redirect_to submission
end

Now every time I try to make a comment submission Rails returns: 现在,每次我尝试提交评论时,Rails都会返回:

ActiveRecord::RecordNotFound in CommentsController#create Couldn't find Submission without an ID or undefined method `answers' for nil:NilClass  

Basically rails isn't pulling the :id from the URL with params and I don't know why. 基本上,rails不会使用params从URL中提取:id,我也不知道为什么。 The submission page displays correctly for each ID in the URL, so I don't get why its not pulling it for this form. 提交页面针对URL中的每个ID正确显示,所以我不明白为什么它不为此表单提取它。 If I name the id explicitly (IE Submission.find(2345)) it works perfectly...so what am I missing? 如果我明确命名ID(IE Submission.find(2345)),它就可以完美运行...所以我缺少了什么? Am I just being stupid? 我只是愚蠢吗?

My relationships are set up properly as well. 我的人际关系也正确建立。

Thanks in advance. 提前致谢。

The following piece of code is generating a form that submits to comments controller: 以下代码段生成一个表单,该表单提交给comments控制器:

<% form_for Comment.new do |f| %> 

I believe you have to pass the the submission id then inside the form: 我相信您必须在表单内传递提交ID,然后再传递:

<%=hidden_field_tag(:submission_id, @submission.id)%>

And inside the comments controller you gotta grap that id: 在注释控制器中,您必须掌握该ID:

def create
    submission = Submission.find(params[:submission_id])
    comment = submission.comments.create(params[:comment])
    comment.created_at = Time.now
    comment.save
    redirect_to submission
end

That should solve it, however I recommend doing nested resources as a second step. 那应该可以解决,但是我建议做嵌套资源作为第二步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM