创建用户评论并编辑?

huangapple go评论66阅读模式
英文:

Create user comments and edit?

问题

以下是您提供的代码的翻译:

在尝试创建用户评论时,我收到以下错误。一旦这个问题得到解决,我打算编辑和删除评论。

ActiveRecord::RecordInvalid in CommentsController#create

验证失败:必须存在用户

comments_controller

class CommentsController < ApplicationController
  before_action :set_post

  http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]

  def create
    @comment = @article.comments.create!(comment_params)
    @comment.user = current_user
    redirect_to article_path(@article), notice: "Comment added successfully"
  end

  def destroy
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article), status: :see_other, notice: "Comment deleted successfully"
  end

  private

  def set_post
    @article = Article.find(params[:article_id])
  end

  def comment_params
    params.require(:comment).permit(:body, :status)
  end
end

comment.rb

class Comment < ApplicationRecord
  # include Visible

  belongs_to :article
  belongs_to :user
  has_rich_text :body
end

article.rb

class Article < ApplicationRecord
  include Visible
  has_many :comments, dependent: :destroy
  belongs_to :user

  validates :title, presence: true, length: { minimum: 1, maximum: 40 }
  validates :body, presence: true, length: { minimum: 10, maximum: 10000 }
end

user.rb

class User < ApplicationRecord

  # 包括默认的 Devise 模块。其他可用的模块有:
  # :confirmable、:lockable、:timeoutable、:trackable 和 :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable

  has_many :articles
  has_many :comments

  def create
    # 从参数中创建用户
    @user = User.new(user_params)
    if @user.save
      # 发送电子邮件
      UserNotifierMailer.send_signup_email(@user).deliver
      redirect_to(@user, :notice => 'User created')
    else
      render :action => 'new'
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :login)
  end

  # 在控制台中使用以下命令设置用户权限:
  # @user = User.first
  # @user.role = 1 # moderator
  # @user.save
  enum role: [:user, :moderator, :admin]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :user
  end

end

schema

这部分是数据库架构定义,没有需要翻译的内容。

routes

Rails.application.routes.draw do
  # 根据 https://guides.rubyonrails.org/routing.html 中的 DSL 定义应用程序路由
  root "articles#home"

  devise_for :users, controllers: {
    sessions: 'users/sessions',
    registrations: 'users/registrations'
  }

  # 允许链式 URL 路由
  # 例如,/posts/1/comments/4
  resources :articles do
    resources :comments
  end
end

comments/edit.rb

<h1>编辑评论</h1>

<%= render 'comments/form', comment: @comment %>

comments/_form.html.erb

<%= form_with model: [@article, @article.comments.build] do |form| %>

<div class="input-group mb-3 w-50">
  <span class="input-group-text"><%= form.label :body %>
  </span>
  <%= form.text_area :body, :class => "form-control", :rows => 8 %>
</div>

<div class="input-group mb-3 w-25">
  <span class="input-group-text"><%= form.label :status %>
  </span>
  <%= form.select :status, options_for_select(['public', 'private', 'archived']), {}, :class => 'form-select' %>
</div>

<%= form.submit :class => "btn btn-primary" %>

<% end %>

comments/_comment.html.erb

<ul class="list-group list-group-flush w-50">
<li class="list-group-item">
  <p>
    <strong>用户:</strong>
    <%= comment.user.username %>
  </p>

  <p>
    <strong>评论:</strong>
    <%= comment.body %>
  </p>

  <p class="timestamp">
    <u>创建于:</u> <%= comment.created_at.strftime("%d %b %y %H:%M:%S") %> 
    <u>更新于:</u> <%= comment.updated_at.strftime("%d %b %y %H:%M:%S") %>
  </p>
  <%= if current_user == comment.user %>
  <p>
    <%= link_to "编辑", edit_article_comment_path(comment.article, comment), :class => "link-primary link-offset-2 link-underline-opacity-0 link-underline-opacity-100-hover me-3" %>
    <%= link_to "删除", [comment.article, comment], :class => "link-danger link-offset-2 link-underline-opacity-0 link-underline-opacity-100-hover", data: {
      turbo_method: :delete,
      turbo_confirm: "您确定吗?"
    } %>
  </p>
  <% end %>

  </li>
  </ul>
  <hr>

这是您提供的代码的翻译部分。如果您需要进一步的帮助或解释,请随时提问。

英文:

When attempting to create a user comment I receive the following errors. I then plan to edit and delete the comments once this is working.

ActiveRecord::RecordInvalid in CommentsController#create

Validation failed: User must exist

comments_controller

class CommentsController &lt; ApplicationController
  before_action :set_post

  http_basic_authenticate_with name: &quot;dhh&quot;, password: &quot;secret&quot;, except: [:index, :show]

  def create
    @comment = @article.comments.create!(comment_params)
    @comment.user = current_user
    redirect_to article_path(@article), notice: &quot;Comment added successfully&quot;
  end

  def destroy
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article), status: :see_other, notice: &quot;Comment deleted successfully&quot;
  end

  private

  def set_post
    @article = Article.find(params[:article_id])
  end

  def comment_params
    params.require(:comment).permit(:body, :status)
  end
end

comment.rb

class Comment &lt; ApplicationRecord
  # include Visible

  belongs_to :article
  belongs_to :user
  has_rich_text :body
end

article.rb

class Article &lt; ApplicationRecord
  include Visible
  has_many :comments, dependent: :destroy
  belongs_to :user   

  validates :title, presence: true, length: {minimum: 1, maximum: 40}
  validates :body, presence: true, length: { minimum: 10, maximum: 10000 }
end

user.rb

class User &lt; ApplicationRecord

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable

  has_many :articles   
  has_many :comments   
  
  def create
    # Create the user form params
    @user = User.new(user_params)
    if @user.save
      # Send the email
      UserNotifierMailer.send_signup_email(@user).deliver
      redirect_to(@user, :notice =&gt; &#39;User created&#39;)
    else
      render :action =&gt; &#39;new&#39;
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :login)
  end

  # set user privileges within console using:
  # @user = User.first
  # @user.role = 1 # moderator
  # @user.save
  enum role: [:user, :moderator, :admin]
  after_initialize :set_default_role, :if =&gt; :new_record?

  def set_default_role
    self.role ||= :user
  end

end

schema

ActiveRecord::Schema[7.0].define(version: 2023_05_19_130034) do
  create_table &quot;action_text_rich_texts&quot;, force: :cascade do |t|
    t.string &quot;name&quot;, null: false
    t.text &quot;body&quot;
    t.string &quot;record_type&quot;, null: false
    t.bigint &quot;record_id&quot;, null: false
    t.datetime &quot;created_at&quot;, null: false
    t.datetime &quot;updated_at&quot;, null: false
    t.index [&quot;record_type&quot;, &quot;record_id&quot;, &quot;name&quot;], name: &quot;index_action_text_rich_texts_uniqueness&quot;, unique: true
  end

  create_table &quot;active_storage_attachments&quot;, force: :cascade do |t|
    t.string &quot;name&quot;, null: false
    t.string &quot;record_type&quot;, null: false
    t.bigint &quot;record_id&quot;, null: false
    t.bigint &quot;blob_id&quot;, null: false
    t.datetime &quot;created_at&quot;, null: false
    t.index [&quot;blob_id&quot;], name: &quot;index_active_storage_attachments_on_blob_id&quot;
    t.index [&quot;record_type&quot;, &quot;record_id&quot;, &quot;name&quot;, &quot;blob_id&quot;], name: &quot;index_active_storage_attachments_uniqueness&quot;, unique: true
  end

  create_table &quot;active_storage_blobs&quot;, force: :cascade do |t|
    t.string &quot;key&quot;, null: false
    t.string &quot;filename&quot;, null: false
    t.string &quot;content_type&quot;
    t.text &quot;metadata&quot;
    t.string &quot;service_name&quot;, null: false
    t.bigint &quot;byte_size&quot;, null: false
    t.string &quot;checksum&quot;
    t.datetime &quot;created_at&quot;, null: false
    t.index [&quot;key&quot;], name: &quot;index_active_storage_blobs_on_key&quot;, unique: true
  end

  create_table &quot;active_storage_variant_records&quot;, force: :cascade do |t|
    t.bigint &quot;blob_id&quot;, null: false
    t.string &quot;variation_digest&quot;, null: false
    t.index [&quot;blob_id&quot;, &quot;variation_digest&quot;], name: &quot;index_active_storage_variant_records_uniqueness&quot;, unique: true
  end

  create_table &quot;articles&quot;, force: :cascade do |t|
    t.string &quot;title&quot;
    t.text &quot;body&quot;
    t.datetime &quot;created_at&quot;, null: false
    t.datetime &quot;updated_at&quot;, null: false
    t.string &quot;status&quot;
    t.integer &quot;user_id&quot;, null: false
    t.integer &quot;views&quot;, default: 0
    t.index [&quot;user_id&quot;], name: &quot;index_articles_on_user_id&quot;
  end

  create_table &quot;comments&quot;, force: :cascade do |t|
    t.string &quot;commenter&quot;
    t.text &quot;body&quot;
    t.integer &quot;article_id&quot;, null: false
    t.datetime &quot;created_at&quot;, null: false
    t.datetime &quot;updated_at&quot;, null: false
    t.string &quot;status&quot;
    t.integer &quot;user_id&quot;, null: false
    t.index [&quot;article_id&quot;], name: &quot;index_comments_on_article_id&quot;
    t.index [&quot;user_id&quot;], name: &quot;index_comments_on_user_id&quot;
  end

  create_table &quot;users&quot;, force: :cascade do |t|
    t.string &quot;email&quot;, default: &quot;&quot;, null: false
    t.string &quot;encrypted_password&quot;, default: &quot;&quot;, null: false
    t.string &quot;reset_password_token&quot;
    t.datetime &quot;reset_password_sent_at&quot;
    t.datetime &quot;remember_created_at&quot;
    t.string &quot;confirmation_token&quot;
    t.datetime &quot;confirmed_at&quot;
    t.datetime &quot;confirmation_sent_at&quot;
    t.string &quot;unconfirmed_email&quot;
    t.integer &quot;role&quot;, default: 0
    t.datetime &quot;created_at&quot;, null: false
    t.datetime &quot;updated_at&quot;, null: false
    t.string &quot;username&quot;
    t.index [&quot;confirmation_token&quot;], name: &quot;index_users_on_confirmation_token&quot;, unique: true
    t.index [&quot;email&quot;], name: &quot;index_users_on_email&quot;, unique: true
    t.index [&quot;reset_password_token&quot;], name: &quot;index_users_on_reset_password_token&quot;, unique: true
  end

  add_foreign_key &quot;active_storage_attachments&quot;, &quot;active_storage_blobs&quot;, column: &quot;blob_id&quot;
  add_foreign_key &quot;active_storage_variant_records&quot;, &quot;active_storage_blobs&quot;, column: &quot;blob_id&quot;
  add_foreign_key &quot;articles&quot;, &quot;users&quot;
  add_foreign_key &quot;comments&quot;, &quot;articles&quot;
  add_foreign_key &quot;comments&quot;, &quot;users&quot;
end

routes

Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
  root &quot;articles#home&quot;

  devise_for :users, controllers: {
    sessions: &#39;users/sessions&#39;,
    registrations: &#39;users/registrations&#39;
  }

  # allows for chained url routes
  # eg. /posts/1/comments/4
  resources :articles do
    resources :comments
  end
end

comments/edit.rb

&lt;h1&gt;Edit comment&lt;/h1&gt;

&lt;%= render &#39;comments/form&#39;, comment: @comment %&gt;

comments/_form.html.erb

&lt;%= form_with model: [@article, @article.comments.build] do |form| %&gt;

&lt;div class=&quot;input-group mb-3 w-50&quot;&gt;
  &lt;span class=&quot;input-group-text&quot;&gt;&lt;%= form.label :body %&gt;
  &lt;/span&gt;
  &lt;%= form.text_area :body, :class =&gt; &quot;form-control&quot;, :rows =&gt; 8 %&gt;
&lt;/div&gt;

&lt;div class=&quot;input-group mb-3 w-25&quot;&gt;
  &lt;span class=&quot;input-group-text&quot;&gt;&lt;%= form.label :status %&gt;
  &lt;/span&gt;
  &lt;%= form.select :status, options_for_select([&#39;public&#39;, &#39;private&#39;, &#39;archived&#39;]), {}, :class =&gt; &#39;form-select&#39; %&gt;
&lt;/div&gt;

&lt;%= form.submit :class =&gt; &quot;btn btn-primary&quot; %&gt;

&lt;% end %&gt;

comments/_comment.html.erb

&lt;ul class=&quot;list-group list-group-flush w-50&quot;&gt;
&lt;li class=&quot;list-group-item&quot;&gt;
  &lt;p&gt;
    &lt;strong&gt;User:&lt;/strong&gt;
  &lt;%= comment.user.username%&gt;
&lt;/p&gt;

&lt;p&gt;
  &lt;strong&gt;Comment:&lt;/strong&gt;
  &lt;%= comment.body%&gt;
&lt;/p&gt;

&lt;p class=&quot;timestamp&quot;&gt;
  &lt;u&gt;Created on:&lt;/u&gt; &lt;%= comment.created_at.strftime(&quot;%d %b %y %H:%M:%S&quot;) %&gt; 
  &lt;u&gt;Updated on:&lt;/u&gt; &lt;%= comment.updated_at.strftime(&quot;%d %b %y %H:%M:%S&quot;) %&gt;
&lt;/p&gt;
&lt;%= if current_user == comment.user %&gt;
&lt;p&gt;
  &lt;%= link_to &quot;Edit&quot;, edit_article_comment_path(comment.article, comment), :class =&gt; &quot;link-primary link-offset-2 link-underline-opacity-0 link-underline-opacity-100-hover me-3&quot; %&gt;
  &lt;%= link_to &quot;Delete&quot;, [comment.article, comment], :class =&gt; &quot;link-danger link-offset-2 link-underline-opacity-0 link-underline-opacity-100-hover&quot;, data: {
    turbo_method: :delete,
    turbo_confirm: &quot;Are you sure?&quot;
  } %&gt;
&lt;/p&gt;
&lt;% end %&gt;

&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;

I have tried following the following but cannot get it to work:
Youtube vid,
this and this

答案1

得分: 1

你正在尝试在关联用户之前创建评论,请尝试以下方式

def create
  @comment = @article.comments.build(comment_params)
  @comment.user = current_user
  @comment.save
  redirect_to article_path(@article), notice: "评论已成功添加"
end
英文:

You are trying to create the comment before associating the user, try this instead

 def create
    @comment = @article.comments.build(comment_params)
    @comment.user = current_user
    @comment.save
    redirect_to article_path(@article), notice: &quot;Comment added successfully&quot;
  end

huangapple
  • 本文由 发表于 2023年5月22日 15:50:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304022.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定