私の Rails アプリには、ユーザーがムービーにコメントできるコメント scaffold があります。
私は2つの問題に直面しています。
最初の問題は、サインインしていなくても、誰でもコメントを作成できることです。ユーザーにコメントを割り当てるにはどうすればcurrent_user
よいでしょうか。コメントは <%= comment.user.first_name %> であり、サインインしていない場合はコメントを作成できません。どうすればいいですか?(私はデバイスを使用しています)
2 つ目の問題は、コメントを作成すると、このパス (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