首页 > 解决方案 > 在 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

我希望将评论推送到数据库中,但实际结果是什么都没做:评论只是被忽略了,我不知道为什么。我已经在这里搜索过,我发现了一个类似问题的主题,但解决方案是我的实际代码。

标签: ruby-on-rails

解决方案


推荐阅读