2017-02-28 19 views
0

我想在停用用戶後一次禁用所有用戶鏈接。所以,我寫了這樣的在Rails5中停用後禁用用戶的所有鏈接

 def link_to(*user) 
     if user_link_disabled?(user.id) 
     return nil 
     else 
     super 
     end 
    end 

    def user_link_disabled?(user_id) 
     User.where(activation: false).pluck(:name).include?(user_id) 
    end 

一個代碼,但我得到這個錯誤

undefined method `id' for #<Array:0x007efee4667d00> 

任何人都可以請幫我在這?

回答

0

我不知道範圍,因爲你沒有顯示任何信息,但它可能只是user_id在你的if語句或嘗試id [params [:id]而不是user.id,但我不確定有更多上下文。

+0

我試過這一個,它現在不顯示錯誤,但鏈接禁用不起作用。 –

0

在下面的方法

def user_link_disabled?(user_id) 
    User.where(activation: false).pluck(:name).include?(user_id) 
end 

您打算從用戶表中的記錄採摘name,但你爲user.id檢查include?,我想你應該摘去id而不是name

0

首先,我不會評論您的首選代碼/方法來覆蓋link_to幫手。沒有太多可用的上下文。

但要解決你所得到的特定錯誤:像這樣def link_to(*user)

你的定義方法。

這裏*user意味着它期待Array作爲方法的參數並使用Ruby splat(*),它將它轉換爲普通參數。

因此,如果您將此稱爲link_to [1,2,3],它將與調用帶3個參數的方法相同。那是link_to (1,2,3),但參數user將是一個數組。

所以在這裏if user_link_disabled?(user.id),你打電話idArray數據類型。這就是爲什麼你得到一個錯誤。 根據您的使用,要麼刪除方法定義*

使用循環,如果你要多個用戶的數據傳遞給方法,如:

def link_to(*user) 
    user.each do |u| 
    if user_link_disabled?(u.id) 
     return nil 
    else 
     super 
    end 
    end 
end 

正如我所提到一開始,我對上下文了解不多。所以不能評論正確的方式,但如果我可以建議,那麼我會建議使用所有用戶路由的自定義助手。像下面的僞代碼:

def link_to_user(user) 
    deactivated = user.deactivated? 
    if deactivated 
    # render some disabled link 
    else 
    # render link 
    end 
end 
+0

我已經使用循環,因爲你建議,但現在我得到這個錯誤。 未定義的方法'ID'的#

+0

我想,那是因爲你正在使用'link_to'以錯誤的方式。它的第一個參數應該是鏈接文本(字符串),然後url(用戶)參數,但在這裏你只有一個,所以它採取的是該參數是一個字符串傳遞它通過緩衝區。嘗試使用[this]這樣的簽名(http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) – Sajan

1

我將列添加到您的用戶模式:

停用=> boolean類型

user.deactivated? #will return true or false 

在你看來,你就可以使用link_to_unless

link_to_unless(user.deactivated, name, options = {}, html_options = {}, &block)