1

User scaffold (DEVISE)、Comments scaffold、movies scaffold があります。

現在、コメントは映画上映ページに投稿されています。

私が問題を抱えているのは、ユーザーがコメントを作成することです。コメントがユーザーによって作成されるようにします。

したがって、コメントをmovies/:show

私はそれをできた

本文:<%= comment.body %> 著者:<%= comment.user.first_name %>

コメントをユーザーに属させ、そのユーザーのみが編集および破棄できるようにするにはどうすればよいですか?

before_filter :authenticate_user!, only: [:create,:destroy] 私はすでにこれらの両方を行っており、動作しないため、マイクロポストでマイケル・ハートル・チュートリアルを使用またはフォローするように言わないでください

とにかく、私がこれを行う方法を知っている人はいますか?

どうもありがとう

4

4 に答える 4

3

最初に、次のように所有者のみにリンクを表示editdestroyます。

<% if comment.user == current_user %>
  <%= link_to "edit", ... %>
  <%= link_to "delete", ... %>
<% end %>

そして念のため、クロムでインスペクト要素を使用する方法を知っている賢い人のために、コメントの所有者に対してコントローラーレベルのチェックを行います。

def edit
  @comment = Comment.find(params[:id])
  if @comment.user == current_user
    @comment.update_attributes(....)
    @message = "Comment updated or created or deleted, depends on method"
  else
    @message = "It's not your comment wise guy :)"
  end
  redirect_to :back, notice: @message
end

destroy メソッドと update メソッドについても同様です。

!コピー/貼り付け可能なコードではありません。

これは私がかつて行ったことであり、非常にうまく機能しました。他の方法では、gem cancan https://github.com/ryanb/cancanを使用して、ユーザーの機能を設定できます。

can :edit, Comment, :user_id => user.id
can :destroy, Comment, :user_id => user.id

このように機能を設定すると、所有者のみが編集ページと更新、破棄アクションにアクセスできます。

于 2013-06-12T17:36:01.297 に答える
1

デバイスヘルパー「current_user」はどうですか? このようなもの:

class Comment < ActiveRecord::Base
  belongs_to :user
end

class CommentsController < ApplicationController
  def edit
    comment = current_user.comments.where(id: params[:id]).first
    if comment.nil?
      ...
      401 error or something else (current user is not creator of this comment)
    else
     ...
    end
   end
end

また、ビューで権限を確認することもできます:

<% if comment.user == current_user %>
  <%= link_to "edit comment" ... %>
  <%= link_to "delete comment" ... %>
<% end %>
于 2013-06-12T17:44:30.280 に答える
0

コメントをユーザーに属するようにするには、createアクションで次のようにします。

comment = current_user.comments.new(params[:comment])

所有者のみが編集可能/破棄可能にするには

before_filter :find_comment, only: [:show, :edit, :update, :destroy]
before_filter :authorize_user!, only: [:edit, :update, :destroy]
#...

private

  def find_comment
    @comment = Comment.find params[:id]
  end

  def authorize_user!
    deny_access if @comment.user != current_user # example
  end
于 2013-06-12T17:42:01.113 に答える
0

ユーザーがサインインしていることを確認するの:authenticate_user!は良いことですが、コメントもユーザーに関連付ける必要があります。

Deviseを与えますcurrent_user。したがって、あなたComment belongs_to :userとあなたUser has_many :commentsがあなたに書いた場合CommentsController:

def new
  @comment= current_user.comments.new
end

def create
  @comment= current_user.comments.new(params[:comment])
  if @comment.save
    ...
  end
end

def edit
  @comment= current_user.comments.find(params[:id])
end

def update
  @comment= current_user.comments.find(params[:id])
  if @comment.update_attributes(params[:comment])
    ...
  end
end
于 2013-06-12T17:44:23.323 に答える