gpt4 book ai didi

ruby-on-rails - 对多个模型的评论

转载 作者:数据小太阳 更新时间:2023-10-29 08:17:21 24 4
gpt4 key购买 nike

在我的 Rails 应用程序中,我目前设置了评论以与我的帖子模型一起使用,该模型运行正常。如何向我的图书模型添加评论?

这是我目前所拥有的:

这是我的评论架构中的内容:

 create_table "comments", force: true do |t|
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
t.integer "post_id"
t.integer "book_id"
end

在我的用户模型中:

class User < ActiveRecord::Base
has_many :comments
acts_as_voter
end

在我的帖子模型中:

class Post < ActiveRecord::Base
has_many :comments
end

在我的书模型中:

class Book < ActiveRecord::Base
has_many :comments
end

在我的评论模型中:

class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :book
belongs_to :user
acts_as_votable
end

在我的评论 Controller 中:

class CommentsController < ApplicationController
def create
post.comments.create(new_comment_params) do |comment|
comment.user = current_user
end
respond_to do |format|
format.html {redirect_to post_path(post)}
end
end


def upvote
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.liked_by current_user

respond_to do |format|
format.html {redirect_to @post}
end
end


private

def new_comment_params
params.require(:comment).permit(:body)
end

def post
@post = Post.find(params[:post_id])
end

end

在我的路线文件中:

resources :posts do
resources :comments do
member do
put "like", to: "comments#upvote"
end
end
end

在我看来:

<% @post.comments.each do |comment| %>
<%= comment.body %>

<% if user_signed_in? && (current_user != comment.user) && !(current_user.voted_for? comment) %>

<%= link_to “up vote”, like_post_comment_path(@post, comment), method: :put %>

<%= comment.votes.size %>

<% else %>

<%= comment.votes.size %></a>

<% end %>
<% end %>


<br />


<%= form_for([@post, @post.comments.build]) do |f| %>

<p><%= f.text_area :body, :cols => "80", :rows => "10" %></p>

<p><%= f.submit “comment” %></p>

<% end %>

我要在我的评论 Controller 中添加什么才能让评论同时适用于帖子和书籍?我应该在我的路线文件中添加什么?

在此先感谢您的帮助。

最佳答案

您不想指定可以容纳 Comment 对象的每种类型的对象。这造成到处都是 if-elsif-else block 的麻烦。相反,您希望事物是 Commentable,并且它们都将具有 .comments

这叫做 polymorphic association在事件记录中。所以你的模型应该是这样的:

class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end

class Post < ActiveRecord::Base
has_many :comments, as: :commentable
end

class Book < ActiveRecord::Base
has_many :comments, as: :commentable
end

并相应地修改您的数据库,所有这些都在链接的文章中。现在,当您为表单构建一个 Comment 对象时,它会预先填充一个 commentable_idcommentable_type,您可以将它们扔到隐藏字段中.现在,Comment 与什么无关紧要,您总是一视同仁。

我会将 User 作为一个单独的关联,因为这并不是一个真正的想法。

关于ruby-on-rails - 对多个模型的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22025288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com