【问题标题】:How can I add 2 arguments to 1 function?如何将 2 个参数添加到 1 个函数?
【发布时间】:2016-10-19 02:14:35
【问题描述】:

我是 Rails 新手,正在学习 Hartl 的教程,但有时我想在代码中添加一些特别的东西。我现在正在做微博,我想添加“删除”功能来删除微博,但我希望这个功能只对管理员和创建这个微博的用户可见。现在我不知道该怎么做,因为当我想设置<% if current_user(micropost.user) && user.admin %> 时,我得到一个错误wrong number of arguments (given 1, expected 0)。 在session_helper.rb 我有函数def current_user 而不是def current_user(micropost.user) 我知道但是我可以以某种方式添加这个micropost.user 并完成这个吗?波纹管所有代码:

app/views/microposts/_micropost.html.erb

<li id="micropost-<%= micropost.id %>">
  <%= link_to gravatar_for(micropost.user, size: 50), micropost.user %>
  <span class="user"><%= link_to micropost.user.name, micropost.user %></span>
  <span class="content"><%= micropost.content %></span>
  <span class="timestamp">
    Posted <%= time_ago_in_words(micropost.created_at) %> ago.
  </span>
  <% if current_user(micropost.user) && user.admin %>
   <%= link_to "delete", micropost, method: :delete,
                         data: { confirm: "You sure?" } %>
  <% end %>
</li>        

app/helpers/session_helper.html.erb

def current_user
  if (user_id = session[:user_id])
    @current_user ||= User.find_by(id: user_id)
  elsif (user_id = cookies.signed[:user_id])
    user = User.find_by(id: user_id)
    if user && user.authenticated?(:remember, cookies[:remember_token])
      log_in user
      @current_user = user
    end
  end
end    

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您应该只检查if current_user == micropost.user。没有理由向current_user 添加参数,这样做会使该方法的目的变得不那么明显。 current_user(something) 方法绝不意味着当前用户和参数之间的相等性检查,并且违反了一个非常常见的 Rails 实践,即定义一个名为 current_user 的方法来返回当前经过身份验证的用户。

    如果你想定义一个附加方法来检查给定用户是否是当前用户,你应该使用current_user?(user)。会这样使用...

    <% if current_user?(micropost.user) && user.admin %>
    

    并定义如下:

    def current_user?(user)
      current_user == user
    end
    

    【讨论】:

    • 太容易了,我没想到。谢谢!
    • 顺便说一句,您对我如何定义管理员功能有什么建议吗?当我以管理员身份单击删除按钮时,我会被重定向到 root_url 而不会删除帖子...
    【解决方案2】:

    meagar 是正确的,您不应该向该方法添加参数。但是要允许参数,您只需将 def 行更改为类似的内容,然后只需在要调用它的地方引用 user 参数,这也是个坏主意,但您是成年人。

    def current_user(user)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-21
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 2017-07-19
      相关资源
      最近更新 更多