2017-02-28 53 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)