在我的 Rails 应用程序中,我有一个评论脚手架,可让用户评论电影。
我面临两个问题。
第一个问题是任何人都可以创建评论,即使他们没有登录,我如何将评论分配给用户,所以如果有current_user
,他们可以创建评论,我可以将用户分配给评论所以 <%= comment.user.first_name %>,如果他们没有登录,他们就不能创建评论。我该怎么做?(我正在使用设计)
第二个问题是,当我创建评论时,它会将我带到这条路径(其中 12 是 :movie_id)
localhost:3000/movies/12/comments/new
这很好,但是当我创建评论时,我必须指定movie_id(12),这是如何自动完成的,所以rails看到评论的movie_id是12。
我的评论控制器,以防需要
class CommentsController < ApplicationController
# GET /comments
# GET /comments.json
before_filter :load_movie
def index
@comments = @movie.comments.all
@search = Movie.search(params[:q])
respond_to do |format|
format.html # index.html.erb
format.json { render json: @comments }
end
end
# GET /comments/1
# GET /comments/1.json
def show
@comment = Comment.find(params[:id])
@search = Movie.search(params[:q])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @comment }
end
end
# GET /comments/new
# GET /comments/new.json
def new
@comment = Comment.new
@search = Movie.search(params[:q])
respond_to do |format|
format.html # new.html.erb
format.json { render json: @comment }
end
end
# GET /comments/1/edit
def edit
@comment = Comment.find(params[:id])
@search = Movie.search(params[:q])
end
# POST /comments
# POST /comments.json
def create
@comment = Comment.new(params[:comment])
@search = Movie.search(params[:q])
respond_to do |format|
if @comment.save
format.html { redirect_to :back }
format.json { render json: @comment, status: :created, location: @comment }
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PUT /comments/1
# PUT /comments/1.json
def update
@comment = Comment.find(params[:id])
@search = Movie.search(params[:q])
respond_to do |format|
if @comment.update_attributes(params[:comment])
format.html { redirect_to (@movie), notice: 'Comment was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url }
format.json { head :no_content }
end
end
private
def load_movie
@movie = Movie.find_by_id(:movie_id)
end
end