2013-06-12 21 views
1

我有一個用戶的支撐架(設計),一個評論的支架和電影腳手架Rails的用戶協會的意見

目前,評論張貼在電影放映頁。

什麼我在與被具有註釋由用戶創建的麻煩。所以評論是由用戶創建的。

所以,如果我顯示在movies/:show

評論我能做

身體:<%= comment.body %> 作者:<%= comment.user.first_name %>

我將如何作出評論屬於用戶,只有編輯和摧毀只能由該用戶?

請不要告訴使用before_filter :authenticate_user!, only: [:create,:destroy] 或跟隨邁克爾·哈特爾教程用微柱,因爲我已經做了這兩個和他們不工作

不管怎麼說,沒有人知道我怎麼能做到這一點?

千恩萬謝

回答

2

首先,我會表現出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 

相同的銷燬和更新方法。

!不是複製/粘貼準備代碼。

這是我做過的一次,它的工作很不錯,其他方法可以使用gem cancanhttps://github.com/ryanb/cancan併爲用戶設置功能。

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

具有設置能力這種方式只有所有者將能夠訪問編輯頁面和更新,銷燬行動。

+0

和'update'!否則,智能用戶將能夠編輯該帖子。 –

+0

是的,你說得對,更新行動你也必須檢查o所有者。謝謝你提到這個。 – rmagnum2002

+0

<%if comment.user == current_user%>這不起作用,因爲它所做的只是說如果有current_user,註釋是可編輯的。此外,我必須更改代碼,因爲使用您提供的代碼時,它隱藏在signed_in用戶身上,就好像我已註銷一樣,我可以看到這些操作。 – PMP

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 
0

確保用戶與:authenticate_user!簽署是個好東西,但你必須有個用戶評論過關聯。

Devise給你一個current_user。所以,如果你Commentbelongs_to :user和你Userhas_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 
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 %>