试图学习RoR.目前正在向用户添加评论.到目前为止,我有一个帖子模型,评论模型和post_comments模型(将两者联系起来).所以对于'rails console',我可以运行:(比如我设置p = Post.first和c = Comment.first)
p.comments << c
这形成一个关联,因此它在控制台中工作.我似乎无法从UI中获得用于形成此关联的注释.到目前为止,我正在"comments/new"创建评论(不确定这是否是问题.是否需要在"发布视图"上创建"发布").
以下是一些代码段
控制器comments_controller.rb
class CommentsController < ApplicationController
def index
@comment = Comment.all
end
def new
@comment = Comment.new
end
def create
@comment = Comment.new(commentParams)
if @comment.save
flash[:success] = "Comment successfully added"
redirect_to comments_path(@comment)
else
render 'new'
end
end
def show
@comment = Comment.find(params[:id])
end
private
def commentParams
params.require(:comment).permit(:comment)
end
end
Run Code Online (Sandbox Code Playgroud)
posts_controller
class PostsController < ApplicationController
before_action :setPost, only: [:edit, :update, :show, :destroy, :sold]
before_action :requireUser, except: [:index, :show]
before_action :requireSameUser, only: …Run Code Online (Sandbox Code Playgroud)