2011-09-07 57 views
1

我有一個控制器,我在做某種時髦的選擇。我有一個邀請表,belongs_to用戶和has_one用戶。在相關模型的控制器中限制用戶的訪問

破壞時的邀請,我希望「HAS_ONE用戶」是做的破壞,是在我的控制,我第一次收到邀請的用戶已被邀請與數組:

def destroy 
    @invitations = Invitation.find_by_recipient_email(current_user.email) 

從這個@invitations數組中,我想使用:id參數進行查找。有沒有辦法做這樣的事情:

@invitations = Invitation.find_by_recipient_email(current_user.email) 
    @invitation = @invitations.find(params[:id]) 

這樣我可以限制用戶只能訪問他們已被邀請上(與CURRENT_USER法)中的那些邀請,然後選擇特定的邀請。我目前無法做到這一點,因爲.find不適用於數組。

感謝您的幫助/指示。

編輯:對不起,我發的帖子那種混亂的,這裏有更多的一些信息:

這裏是我的整個銷燬方法,現在,我只希望刪除一條記錄:

def destroy 
    @invitations = Invitation.find_by_recipient_email(current_user.email) 
    @invitation = @invitations.find(params[:id]) 

    if @invitation.destroy 
     redirect_to invitations_path, :notice => "Declined invitation" 
    else 
     redirect_to :back 
    end 
    end 

我的邀請對象看起來像:

Invitation(id: integer, list_id: integer, sender_id: integer, recipient_email: string, created_at: datetime, updated_at: datetime) 

其中send_id和recipient_email是兩個不同的用戶。

我invitation.rb:

belongs_to :sender, :class_name => 'User' 
    has_one :recipient, :class_name => 'User' 

也許問題是我會打電話像current_users.invitations.find(PARAMS [:編號])和重做了我的邀請模式?

回答

2

你可以只是這樣做:

invitatation_scope = Invitation.where(["recipient_email = ?",current_user.email]) 
@invitation = invitation_scope.find(params[:id])

但你應該使用的before_filter:

before_filter :load_user_invitation, :only=>[:edit,:update,:destroy] 

def load_user_invitation 
    @invitation = Invitation.where(["recipient_email = ?",current_user.email]).find(params[:id]) 
end 
2

find是一種ActiveRecord方法。您可以使用Ruby枚舉方法select返回一組匹配元素,然後將您的邀請從數組中取出。

inv = @invitations.select { |i| i.id == params[:id] } 
@inviation = inv.empty? ? nil : inv[0]