Kat*_*e H 2 ruby ruby-on-rails crud ruby-on-rails-4
在我的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
Run Code Online (Sandbox Code Playgroud)
在我的用户模型中:
class User < ActiveRecord::Base
has_many :comments
acts_as_voter
end
Run Code Online (Sandbox Code Playgroud)
在我的帖子模型中:
class Post < ActiveRecord::Base
has_many :comments
end
Run Code Online (Sandbox Code Playgroud)
在我的书模型中:
class Book < ActiveRecord::Base
has_many :comments
end
Run Code Online (Sandbox Code Playgroud)
在我的评论模型中:
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :book
belongs_to :user
acts_as_votable
end
Run Code Online (Sandbox Code Playgroud)
在我的评论控制器中:
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
Run Code Online (Sandbox Code Playgroud)
在我的路线文件中:
resources :posts do
resources :comments do
member do
put "like", to: "comments#upvote"
end
end
end
Run Code Online (Sandbox Code Playgroud)
在我看来:
<% @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 %>
Run Code Online (Sandbox Code Playgroud)
我将哪些内容添加到我的评论控制器中以获取有关帖子和书籍的评论?我将什么添加到我的路线文件中?
在此先感谢您的帮助.
Nic*_*eys 10
您不希望指定可以容纳Comment对象的每种类型的对象.这造成if-elsif-else了整个地方的街区头痛.相反,你想要的东西Commentable,他们都将拥有.comments它们.
这在Active Record中称为多态关联.所以你会让你的模型像:
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
Run Code Online (Sandbox Code Playgroud)
并相应地修改您的数据库,这些都在链接的文章中.现在,当您Comment为表单构建一个对象时,它将预先填充一个commentable_id和commentable_type,您可以在隐藏的字段中进行折腾.现在无关紧要Comment,你总是把它当作同样的东西.
我将User作为一个单独的协会离开,因为它不是真的相同的想法.