如何将多个值传递给 Rails 中的创建操作?
在我的应用程序中,我有 User
、Post
和 Comment
模型。
当User
想要对Post
发表评论时,Comments
控制器中的新操作将接管。显示帖子
(待评论),并且用户
输入他的评论
。
但是,当用户提交时,我想将 Post.id 和 Comments.content 传递给创建操作。我该怎么做?
这是comments/new.html.erb
<%= form_for @comment do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit "Done" %>
</div>
<% end %>
谢谢大家。我做了嵌套路由,我的 new.html.erb 现在有
<%= form_for [@post,@comment] do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<% f.hidden_field :post %>
<div class="field">
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit "Done" %>
</div>
<% end %>
但是我得到:未定义的方法“注释”,我无法弄清楚那个错误。
In my app I have User
, Post
and Comment
models.
When a User
wants to comment on Post
the new action from the Comments
controller takes over. The Post
(to be commented on) is shown and the User
enters his Comment
.
However, when the User submits, I want to pass the Post.id and the Comments.content to the create action. How do I do that?
Here is the comments/new.html.erb
<%= form_for @comment do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit "Done" %>
</div>
<% end %>
Thanks to all of you. I did the nested routing and my new.html.erb now has
<%= form_for [@post,@comment] do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<% f.hidden_field :post %>
<div class="field">
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit "Done" %>
</div>
<% end %>
However I get: undefined method `comment' and I cant figure that bugger out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的猜测是,每个
Comment
必须属于一个Post
如果是这种情况,那么这似乎是嵌套路由的完美候选者。 http://guides.rubyonrails.org/routing.html#nested-resources因此,在您的情况下,帖子 id 和评论 id 都将成为 URL 的一部分:
您需要在评论控制器操作中处理 post_id 。
My guess is that each
Comment
must belong to aPost
If that's the case then this seems like the perfect candidate for nested routes. http://guides.rubyonrails.org/routing.html#nested-resourcesSo in your case both the post id and the comment id would be part of the URL:
You would need to handle the post_id in your comments controller actions.
首先,您必须将
Post.id
传递给评论新操作。就像我假设您遵循约定,因此
params[ :id ]
是Post.id
。稍后在您的Comment#create
中实例化新评论,用于创建与帖子相关的评论。最后形成新评论
First of all you have to pass
Post.id
to the comments new action. Something likeI assume that you're following conventions so
params[ :id ]
isPost.id
. Later in yourComment#create
instantiate new comment withwhich will create comment related to the post. Finally form for new comment
在视图(使用 HAML)
和 Comment#new 控制器中:
In the view (using HAML)
and in the Comment#new controller: