0

我对传入和传出 Rails 视图助手的参数和结果的处理感到困惑:

module CasesHelper
    def case_owned(owner,cur_usr)       
        return false if (owner.nil?)
        return false if (cur_usr.nil?)
        x = User.find(cur_usr)
        y = User.find(owner)  

        ## this does not returns 'true' 
        ## when expected 
        ## return true if (owner == cur_usr)

        return true if (x == y)     #<<<< This line works
        return false
    end
end

这是视图代码:

    <td><%= link_to 'Show', c %></td>
    <td><%= (link_to 'Edit', edit_case_path(c)) if case_owned(c.user_id,current_user) %></td>
    <td><%= (link_to 'Destroy', c, method: :delete, data: { confirm: 'Are you sure?' })  if case_owned(c.user_id,current_user) %></td>

工作代码如何工作而注释掉的行不能工作?为什么需要 User.find() 调用来确保平等。并且,如何:

   User.find(cur_usr) == User.find(owner)

...评估为true

什么时候:

   cur_usr == owner

...评估为false

我正在使用 Devise gem 进行身份验证,它提供了 current_user 方法。我最初使用“cur_usr == owner”行对上面的代码进行了编码,但意识到使用 User.find() 方法有效。我很困惑传递给 find() 的参数如何被认为是不相等的,但返回的对象(记录)被评估为相等。我在这里想念什么?

请尝试将您的评论指向 Ruby 如何处理将对象作为参数传递或 Rails 命名约定如何在这里“提供帮助”。提前致谢!

4

1 回答 1

1

current_user通常返回一个User实例,如果你运行它,它工作正常User.find(cur_user)(它返回相同的用户)。但是,您的第一个参数是一个 id (c.user_id在视图中)。你可以做owner == cur_user.id

如果您总是希望方法中有一个 ID,您可能应该将变量命名为owner_id

于 2012-10-10T05:20:58.277 回答