Rails:论坛 has_many 主题,保存关联吗?
我可能一开始就以错误的方式来处理这个问题,所以我首先会介绍一些背景知识。
正如您从标题中可以看出的,我正在从头开始构建一个论坛。我以为它工作正常;但是,我有点不确定如何从控制器的主题“创建”方法中更新/保存论坛对象。
我尝试做的事情: 在“New”方法中,我通过路由发送了论坛的 id。因此,在新主题页面上有一个如下所示的地址:“localhost:3000/new-topic/1”。其中一个是论坛的 id。在方法本身中,我尝试将其附加到新的主题对象。
@topic = Topic.new
@topic.forum = Forum.find(params[:id])
然后我的创建方法尝试使用该论坛。
@topic = Topic.new(params[:topic])
@topic.forum.topics << @topic #Simplified down.
if @topic.save
@topic.forum.save
...
我感觉我处理这件事的方式是错误的。我正在看某人的教程,他们通过调用 params[:forum_id] 获得了论坛,但他们没有显示他们为实现这一目标所做的路由。
我如何正确地执行此操作和/或路由所有这些的正确方法是什么?作为记录,我确实计划对主题 => 使用相同的方法邮政协会。感谢您的任何帮助。
I might be going about this the wrong way in the first place, so I will give a bit of background first.
As you can tell from the title, I am building a forum from scratch. I thought it was working correctly; however, I am a bit unsure as to how to update/save the forum object from within the topics "create" method in it's controller.
What I tried to do:
In the "New" method, I sent the Forum's id via the routing. So on the new-topic page has a address that looks like this: "localhost:3000/new-topic/1". The one being the Forum's id. In the method itself, I try to attach it to the new topic object.
@topic = Topic.new
@topic.forum = Forum.find(params[:id])
My create method then tries to use that forum.
@topic = Topic.new(params[:topic])
@topic.forum.topics << @topic #Simplified down.
if @topic.save
@topic.forum.save
...
I get the feeling that I am going about this the wrong way. I was looking at someone's tutorial and they got the forum by calling params[:forum_id] but they didn't show they routing they did to achieve that.
How do I do this correctly and/or what is the correct way to route all of this? For the record, I do plan on using this same method for the Topic => Post association. Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用嵌套的 REST 路由:
这将导致以下路由:
并且在控制器中您应该使用构建器,它们具有安全性、范围保留等多个优点:
http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources
You should use nested REST routes:
this will result in the following routes:
and in controller you should use builders, they have several advantages like security, scope preserving etc.:
http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources