[英]Rails Comments User + Id
在我的Rails應用程序中,我有一個評論支架,可讓用戶對電影發表評論。
我面臨兩個問題。
第一個問題是,即使沒有登錄,任何人都可以創建評論,我將如何為用戶分配評論,因此,如果有current_user
,他們可以創建評論,並且我可以分配用戶注釋,因此<%= comment.user.first_name%>,如果未登錄,則無法創建注釋。 我該怎么辦? (我正在使用devise)
第二個問題是,當我創建評論時,它將帶我到此路徑(其中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
第一:
使用devise,您可以通過在控制器頂部說一句來請求用戶登錄:
before_filter :authenticate_user!, only: [:new,:create]
因此,如果未登錄的用戶嘗試訪問這些操作,則會將其重定向到登錄頁面,並在登錄后轉發到原始請求。
第二:
從路由中可以看到,將12分配給params [:movie_id]。 所以,在你的控制器new
的行動寫:
@movie = Movie.find(params[:movie_id])
@comment = @movie.comments.new
@comment.user=current_user
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.