【发布时间】:2017-01-12 15:35:36
【问题描述】:
我正在创建一个论坛。我已经成功创建了一个 Post 模型,该模型在 html 视图中使用用户电子邮件和 created_at 时间呈现帖子。我还创建了一个评论模型来回复帖子。我一直在学习教程并了解其中的大部分内容,但是现在我迷失了从数据库中获取 cmets 的 user 和 created_at 值,以便我可以显示它们。即使我使用 post 模型执行此操作,它也有所不同,因为我使用的是在 Post 控制器的 show html 视图中显示的部分,而且 post 和 cmets 都显示在 post 控制器显示视图中,这让我感到困惑。 (即 cmets 没有自己的展示视图)。我是新手。任何帮助,将不胜感激。谢谢。
routes.rb
Rails.application.routes.draw do
devise_for :users
resources :posts do
resources :comments
end
root 'posts#index'
end
create_cmets 的迁移
class CreateComments < ActiveRecord::Migration[5.0]
def change
create_table :comments do |t|
t.text :comment
t.references :post, foreign_key: true
t.references :user, foreign_key: true
t.timestamps
end
end
end
cmets_controller.rb
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:comment))
@comment.user = current_user
if @comment.save
redirect_to post_path(@post)
else
render 'new'
end
end
end
_form.html.haml
= simple_form_for([@post, @post.comments.new]) do |f|
= f.input :comment
= f.submit
models/comment.rb
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
end
show.html.haml
#post_content
%h1= @post.title
- if user_allowed_post
= link_to "Delete", post_path(@post), method: :delete, data: { confirm: "Are you sure you want to delete this?"}, class: "button"
= link_to "Edit", edit_post_path(@post), class: "button"
- else
%br
%br
%br
%p= @post.content
%p
Published
= time_ago_in_words(@post.created_at)
by
= @post.user.email
#comments
%h2
- if @post.comments.size == 1
= @post.comments.size
Comment
- else
= @post.comments.size
Comments
= render @post.comments
%h3 Reply to thread
= render "comments/form"
如果您需要任何其他文件或信息,请告诉我。
【问题讨论】:
-
@comment = @post.comments.create(params[:comment].permit(:comment))这条线是做什么的?试试这个@comment = @post.comments.create(params.require(:comment).permit(:post_id).merge!(user_id: current_user.id))并且,试试rails console什么数据实际上保存在数据库中。 -
对不起伙计,我问错了问题,我以为是问题所在,但它有点不同,只是编辑了问题,如果你有时间再读一遍,thnx
-
如果您从
PostsController渲染show动作,那么您必须定义@post并且在其下方您可以使用@comments = @post.comments为该帖子收集cmets。从您可以渲染部分视图,例如:render @comments -
我只是把show html view文件放上去。如何从数据库中获取我创建的 cmets 的 user 和 created-at 值?
-
局部变量
comment将在您的部分= render @post.comments中提供给您。你应该能够做到这一点= comment.user和= comment.created_at
标签: ruby-on-rails time comments