ruby-on-rails - 在 ruby on rails 中创建具有多个关联的对象
问题描述
我有 3 个对象:我想要的文章、评论和用户,当评论与表单一起发布时,评论与文章和用户相关联。
当我只有文章和评论时,它是完美的:我们可以发送表单,创建评论,然后显示。
评论表格:
<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>
<p>
<%= form.label :body %><br>
<%= form.text_area(:body, {:class => 'form-control'} ) %>
</p>
<p>
<%= form.submit({:class => 'btn btn-success'}) %>
</p>
<% end %>
CommentsController 的创建方法:
before_action :authenticate_user!
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.build(comment_params)
@comment.commenter = current_user
@comment.save
redirect_to article_path(@article)
end
和型号:
class Comment < ApplicationRecord
belongs_to :article
belongs_to :user
end
class User < ApplicationRecord
has_many :comments, dependent: :destroy
# Some devise things
end
class Comment < ApplicationRecord
belongs_to :article
belongs_to :user
end
我希望将评论推送到数据库中,但实际结果是什么都没做:评论只是被忽略了,我不知道为什么。我已经在这里搜索过,我发现了一个类似问题的主题,但解决方案是我的实际代码。
解决方案
推荐阅读
- node.js - PascalCase 的正则表达式问题没有击中第一个单词
- javascript - Javascript对象结构区别
- mysql - 如何从 Digital Ocean 管理的数据库中导出 MySQL 数据库
- python - 如何在熊猫对象的价格列中附加一个字符
- node.js - 如何优化具有大量节点模块的反应应用程序的 docker 构建
- c - 编译错误:语句无效
- opc-ua - OPC UA TranslateBrowsePathsToNodeIds:如何稳定/易失地解析 NodeID
- python - 如何更改数据在 mongoDB 数据字段中的位置?
- linux - 从特定用户拥有的特定目录中删除 Linux 中的文件的命令是什么?
- vue.js - 在 Vue 中,如何将特殊的 $event 变量作为参数传递?