创建用户评论并编辑?

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

Create user comments and edit?

问题

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

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

ActiveRecord::RecordInvalid in CommentsController#create

验证失败:必须存在用户

comments_controller

  1. class CommentsController < ApplicationController
  2. before_action :set_post
  3. http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
  4. def create
  5. @comment = @article.comments.create!(comment_params)
  6. @comment.user = current_user
  7. redirect_to article_path(@article), notice: "Comment added successfully"
  8. end
  9. def destroy
  10. @comment = @article.comments.find(params[:id])
  11. @comment.destroy
  12. redirect_to article_path(@article), status: :see_other, notice: "Comment deleted successfully"
  13. end
  14. private
  15. def set_post
  16. @article = Article.find(params[:article_id])
  17. end
  18. def comment_params
  19. params.require(:comment).permit(:body, :status)
  20. end
  21. end

comment.rb

  1. class Comment < ApplicationRecord
  2. # include Visible
  3. belongs_to :article
  4. belongs_to :user
  5. has_rich_text :body
  6. end

article.rb

  1. class Article < ApplicationRecord
  2. include Visible
  3. has_many :comments, dependent: :destroy
  4. belongs_to :user
  5. validates :title, presence: true, length: { minimum: 1, maximum: 40 }
  6. validates :body, presence: true, length: { minimum: 10, maximum: 10000 }
  7. end

user.rb

  1. class User < ApplicationRecord
  2. # 包括默认的 Devise 模块。其他可用的模块有:
  3. # :confirmable、:lockable、:timeoutable、:trackable 和 :omniauthable
  4. devise :database_authenticatable, :registerable,
  5. :recoverable, :rememberable, :validatable, :confirmable
  6. has_many :articles
  7. has_many :comments
  8. def create
  9. # 从参数中创建用户
  10. @user = User.new(user_params)
  11. if @user.save
  12. # 发送电子邮件
  13. UserNotifierMailer.send_signup_email(@user).deliver
  14. redirect_to(@user, :notice => 'User created')
  15. else
  16. render :action => 'new'
  17. end
  18. end
  19. private
  20. def user_params
  21. params.require(:user).permit(:name, :email, :login)
  22. end
  23. # 在控制台中使用以下命令设置用户权限:
  24. # @user = User.first
  25. # @user.role = 1 # moderator
  26. # @user.save
  27. enum role: [:user, :moderator, :admin]
  28. after_initialize :set_default_role, :if => :new_record?
  29. def set_default_role
  30. self.role ||= :user
  31. end
  32. end

schema

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

routes

  1. Rails.application.routes.draw do
  2. # 根据 https://guides.rubyonrails.org/routing.html 中的 DSL 定义应用程序路由
  3. root "articles#home"
  4. devise_for :users, controllers: {
  5. sessions: 'users/sessions',
  6. registrations: 'users/registrations'
  7. }
  8. # 允许链式 URL 路由
  9. # 例如,/posts/1/comments/4
  10. resources :articles do
  11. resources :comments
  12. end
  13. end

comments/edit.rb

  1. <h1>编辑评论</h1>
  2. <%= render 'comments/form', comment: @comment %>

comments/_form.html.erb

  1. <%= form_with model: [@article, @article.comments.build] do |form| %>
  2. <div class="input-group mb-3 w-50">
  3. <span class="input-group-text"><%= form.label :body %>
  4. </span>
  5. <%= form.text_area :body, :class => "form-control", :rows => 8 %>
  6. </div>
  7. <div class="input-group mb-3 w-25">
  8. <span class="input-group-text"><%= form.label :status %>
  9. </span>
  10. <%= form.select :status, options_for_select(['public', 'private', 'archived']), {}, :class => 'form-select' %>
  11. </div>
  12. <%= form.submit :class => "btn btn-primary" %>
  13. <% end %>

comments/_comment.html.erb

  1. <ul class="list-group list-group-flush w-50">
  2. <li class="list-group-item">
  3. <p>
  4. <strong>用户:</strong>
  5. <%= comment.user.username %>
  6. </p>
  7. <p>
  8. <strong>评论:</strong>
  9. <%= comment.body %>
  10. </p>
  11. <p class="timestamp">
  12. <u>创建于:</u> <%= comment.created_at.strftime("%d %b %y %H:%M:%S") %>
  13. <u>更新于:</u> <%= comment.updated_at.strftime("%d %b %y %H:%M:%S") %>
  14. </p>
  15. <%= if current_user == comment.user %>
  16. <p>
  17. <%= 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" %>
  18. <%= link_to "删除", [comment.article, comment], :class => "link-danger link-offset-2 link-underline-opacity-0 link-underline-opacity-100-hover", data: {
  19. turbo_method: :delete,
  20. turbo_confirm: "您确定吗?"
  21. } %>
  22. </p>
  23. <% end %>
  24. </li>
  25. </ul>
  26. <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

  1. class CommentsController &lt; ApplicationController
  2. before_action :set_post
  3. http_basic_authenticate_with name: &quot;dhh&quot;, password: &quot;secret&quot;, except: [:index, :show]
  4. def create
  5. @comment = @article.comments.create!(comment_params)
  6. @comment.user = current_user
  7. redirect_to article_path(@article), notice: &quot;Comment added successfully&quot;
  8. end
  9. def destroy
  10. @comment = @article.comments.find(params[:id])
  11. @comment.destroy
  12. redirect_to article_path(@article), status: :see_other, notice: &quot;Comment deleted successfully&quot;
  13. end
  14. private
  15. def set_post
  16. @article = Article.find(params[:article_id])
  17. end
  18. def comment_params
  19. params.require(:comment).permit(:body, :status)
  20. end
  21. end

comment.rb

  1. class Comment &lt; ApplicationRecord
  2. # include Visible
  3. belongs_to :article
  4. belongs_to :user
  5. has_rich_text :body
  6. end

article.rb

  1. class Article &lt; ApplicationRecord
  2. include Visible
  3. has_many :comments, dependent: :destroy
  4. belongs_to :user
  5. validates :title, presence: true, length: {minimum: 1, maximum: 40}
  6. validates :body, presence: true, length: { minimum: 10, maximum: 10000 }
  7. end

user.rb

  1. class User &lt; ApplicationRecord
  2. # Include default devise modules. Others available are:
  3. # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  4. devise :database_authenticatable, :registerable,
  5. :recoverable, :rememberable, :validatable, :confirmable
  6. has_many :articles
  7. has_many :comments
  8. def create
  9. # Create the user form params
  10. @user = User.new(user_params)
  11. if @user.save
  12. # Send the email
  13. UserNotifierMailer.send_signup_email(@user).deliver
  14. redirect_to(@user, :notice =&gt; &#39;User created&#39;)
  15. else
  16. render :action =&gt; &#39;new&#39;
  17. end
  18. end
  19. private
  20. def user_params
  21. params.require(:user).permit(:name, :email, :login)
  22. end
  23. # set user privileges within console using:
  24. # @user = User.first
  25. # @user.role = 1 # moderator
  26. # @user.save
  27. enum role: [:user, :moderator, :admin]
  28. after_initialize :set_default_role, :if =&gt; :new_record?
  29. def set_default_role
  30. self.role ||= :user
  31. end
  32. end

schema

  1. ActiveRecord::Schema[7.0].define(version: 2023_05_19_130034) do
  2. create_table &quot;action_text_rich_texts&quot;, force: :cascade do |t|
  3. t.string &quot;name&quot;, null: false
  4. t.text &quot;body&quot;
  5. t.string &quot;record_type&quot;, null: false
  6. t.bigint &quot;record_id&quot;, null: false
  7. t.datetime &quot;created_at&quot;, null: false
  8. t.datetime &quot;updated_at&quot;, null: false
  9. t.index [&quot;record_type&quot;, &quot;record_id&quot;, &quot;name&quot;], name: &quot;index_action_text_rich_texts_uniqueness&quot;, unique: true
  10. end
  11. create_table &quot;active_storage_attachments&quot;, force: :cascade do |t|
  12. t.string &quot;name&quot;, null: false
  13. t.string &quot;record_type&quot;, null: false
  14. t.bigint &quot;record_id&quot;, null: false
  15. t.bigint &quot;blob_id&quot;, null: false
  16. t.datetime &quot;created_at&quot;, null: false
  17. t.index [&quot;blob_id&quot;], name: &quot;index_active_storage_attachments_on_blob_id&quot;
  18. 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
  19. end
  20. create_table &quot;active_storage_blobs&quot;, force: :cascade do |t|
  21. t.string &quot;key&quot;, null: false
  22. t.string &quot;filename&quot;, null: false
  23. t.string &quot;content_type&quot;
  24. t.text &quot;metadata&quot;
  25. t.string &quot;service_name&quot;, null: false
  26. t.bigint &quot;byte_size&quot;, null: false
  27. t.string &quot;checksum&quot;
  28. t.datetime &quot;created_at&quot;, null: false
  29. t.index [&quot;key&quot;], name: &quot;index_active_storage_blobs_on_key&quot;, unique: true
  30. end
  31. create_table &quot;active_storage_variant_records&quot;, force: :cascade do |t|
  32. t.bigint &quot;blob_id&quot;, null: false
  33. t.string &quot;variation_digest&quot;, null: false
  34. t.index [&quot;blob_id&quot;, &quot;variation_digest&quot;], name: &quot;index_active_storage_variant_records_uniqueness&quot;, unique: true
  35. end
  36. create_table &quot;articles&quot;, force: :cascade do |t|
  37. t.string &quot;title&quot;
  38. t.text &quot;body&quot;
  39. t.datetime &quot;created_at&quot;, null: false
  40. t.datetime &quot;updated_at&quot;, null: false
  41. t.string &quot;status&quot;
  42. t.integer &quot;user_id&quot;, null: false
  43. t.integer &quot;views&quot;, default: 0
  44. t.index [&quot;user_id&quot;], name: &quot;index_articles_on_user_id&quot;
  45. end
  46. create_table &quot;comments&quot;, force: :cascade do |t|
  47. t.string &quot;commenter&quot;
  48. t.text &quot;body&quot;
  49. t.integer &quot;article_id&quot;, null: false
  50. t.datetime &quot;created_at&quot;, null: false
  51. t.datetime &quot;updated_at&quot;, null: false
  52. t.string &quot;status&quot;
  53. t.integer &quot;user_id&quot;, null: false
  54. t.index [&quot;article_id&quot;], name: &quot;index_comments_on_article_id&quot;
  55. t.index [&quot;user_id&quot;], name: &quot;index_comments_on_user_id&quot;
  56. end
  57. create_table &quot;users&quot;, force: :cascade do |t|
  58. t.string &quot;email&quot;, default: &quot;&quot;, null: false
  59. t.string &quot;encrypted_password&quot;, default: &quot;&quot;, null: false
  60. t.string &quot;reset_password_token&quot;
  61. t.datetime &quot;reset_password_sent_at&quot;
  62. t.datetime &quot;remember_created_at&quot;
  63. t.string &quot;confirmation_token&quot;
  64. t.datetime &quot;confirmed_at&quot;
  65. t.datetime &quot;confirmation_sent_at&quot;
  66. t.string &quot;unconfirmed_email&quot;
  67. t.integer &quot;role&quot;, default: 0
  68. t.datetime &quot;created_at&quot;, null: false
  69. t.datetime &quot;updated_at&quot;, null: false
  70. t.string &quot;username&quot;
  71. t.index [&quot;confirmation_token&quot;], name: &quot;index_users_on_confirmation_token&quot;, unique: true
  72. t.index [&quot;email&quot;], name: &quot;index_users_on_email&quot;, unique: true
  73. t.index [&quot;reset_password_token&quot;], name: &quot;index_users_on_reset_password_token&quot;, unique: true
  74. end
  75. add_foreign_key &quot;active_storage_attachments&quot;, &quot;active_storage_blobs&quot;, column: &quot;blob_id&quot;
  76. add_foreign_key &quot;active_storage_variant_records&quot;, &quot;active_storage_blobs&quot;, column: &quot;blob_id&quot;
  77. add_foreign_key &quot;articles&quot;, &quot;users&quot;
  78. add_foreign_key &quot;comments&quot;, &quot;articles&quot;
  79. add_foreign_key &quot;comments&quot;, &quot;users&quot;
  80. end

routes

  1. Rails.application.routes.draw do
  2. # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
  3. root &quot;articles#home&quot;
  4. devise_for :users, controllers: {
  5. sessions: &#39;users/sessions&#39;,
  6. registrations: &#39;users/registrations&#39;
  7. }
  8. # allows for chained url routes
  9. # eg. /posts/1/comments/4
  10. resources :articles do
  11. resources :comments
  12. end
  13. end

comments/edit.rb

  1. &lt;h1&gt;Edit comment&lt;/h1&gt;
  2. &lt;%= render &#39;comments/form&#39;, comment: @comment %&gt;

comments/_form.html.erb

  1. &lt;%= form_with model: [@article, @article.comments.build] do |form| %&gt;
  2. &lt;div class=&quot;input-group mb-3 w-50&quot;&gt;
  3. &lt;span class=&quot;input-group-text&quot;&gt;&lt;%= form.label :body %&gt;
  4. &lt;/span&gt;
  5. &lt;%= form.text_area :body, :class =&gt; &quot;form-control&quot;, :rows =&gt; 8 %&gt;
  6. &lt;/div&gt;
  7. &lt;div class=&quot;input-group mb-3 w-25&quot;&gt;
  8. &lt;span class=&quot;input-group-text&quot;&gt;&lt;%= form.label :status %&gt;
  9. &lt;/span&gt;
  10. &lt;%= form.select :status, options_for_select([&#39;public&#39;, &#39;private&#39;, &#39;archived&#39;]), {}, :class =&gt; &#39;form-select&#39; %&gt;
  11. &lt;/div&gt;
  12. &lt;%= form.submit :class =&gt; &quot;btn btn-primary&quot; %&gt;
  13. &lt;% end %&gt;

comments/_comment.html.erb

  1. &lt;ul class=&quot;list-group list-group-flush w-50&quot;&gt;
  2. &lt;li class=&quot;list-group-item&quot;&gt;
  3. &lt;p&gt;
  4. &lt;strong&gt;User:&lt;/strong&gt;
  5. &lt;%= comment.user.username%&gt;
  6. &lt;/p&gt;
  7. &lt;p&gt;
  8. &lt;strong&gt;Comment:&lt;/strong&gt;
  9. &lt;%= comment.body%&gt;
  10. &lt;/p&gt;
  11. &lt;p class=&quot;timestamp&quot;&gt;
  12. &lt;u&gt;Created on:&lt;/u&gt; &lt;%= comment.created_at.strftime(&quot;%d %b %y %H:%M:%S&quot;) %&gt;
  13. &lt;u&gt;Updated on:&lt;/u&gt; &lt;%= comment.updated_at.strftime(&quot;%d %b %y %H:%M:%S&quot;) %&gt;
  14. &lt;/p&gt;
  15. &lt;%= if current_user == comment.user %&gt;
  16. &lt;p&gt;
  17. &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;
  18. &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: {
  19. turbo_method: :delete,
  20. turbo_confirm: &quot;Are you sure?&quot;
  21. } %&gt;
  22. &lt;/p&gt;
  23. &lt;% end %&gt;
  24. &lt;/li&gt;
  25. &lt;/ul&gt;
  26. &lt;hr&gt;

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

答案1

得分: 1

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

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

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

  1. def create
  2. @comment = @article.comments.build(comment_params)
  3. @comment.user = current_user
  4. @comment.save
  5. redirect_to article_path(@article), notice: &quot;Comment added successfully&quot;
  6. 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:

确定