ruby-on-rails - 当您可以只使用 "="(来自 Hartl 的教程)时,为什么需要分配方法?

标签 ruby-on-rails ruby railstutorial.org

我很难理解所需的赋值函数,如 chapter 8.2.3 中所述. Hartl 的教程。

作为上下文,他专注于以下 sign_in 函数的第二行:

  def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user #<-- this line
  end

他提到因为它是一个作业,所以必须单独定义为

def current_user=(user)
    @current_user = user
end

方法 current_user= 明确设计用于处理 assignmentcurrent_user。我的困惑是:

  1. 为什么这是必要的?我认为一个简单的 = 可以让你分配东西。例如 user.email = hello@kitty.com

  2. 此外,当他最终将编码 redirect_to current_user 时,属于 SessionsController 的内容如何转换为由 UsersController< 控制的 View ?

谢谢!!

最佳答案

之所以需要它是为了避免方法调用和变量赋值之间的混淆(对于解释器/VM)

def foo
  # Two completely different things!
  bar = "baz" # assigns baz to local variable bar
  self.bar = "baz" # invokes the bar= method with parameter of baz
end

他正在做两件事,首先是用用户对象调用 current_user= 方法,其次是将其设置为 @current_user(这不是一个很好的例子 - 如果您要创建 current_user= 方法(例如设置 session 变量),您最终可能会在现实生活中做更多的事情。

其次,redirect_to current_user 等同于 redirect_to user_path(current_user) - 查看 http://api.rubyonrails.org/classes/ActionController/Redirecting.html有关解释 redirect_to 可以采用的不同参数类型的更多详细信息。请注意,这是重定向,而不是呈现 - 因此此处会发生第二个 HTTP 请求。

关于ruby-on-rails - 当您可以只使用 "="(来自 Hartl 的教程)时,为什么需要分配方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13944163/

相关文章:

ruby-on-rails - 在Rails中创建所见即所得的表单生成器(la Wufoo)

javascript - rails : How to create javascript object from controller?

javascript - 使用 ruby​​ 在 js 文件中使用来自 localhost 的 json 数据

ruby-on-rails - 我可以在 RSpec 请求中访问 Application Helper 方法吗?

ruby-on-rails - 连接到 gmail 时 Rails 3.1.0.rc5 中的 Net::SMTPAuthenticationError

ruby-on-rails - 使用像 facebook 这样的 omniauth 提供程序时,设计不会正确重定向到存储的位置

ruby-on-rails - Rails : import timestamps, 不同时区和夏令时

mysql - rails 上的 ruby : rake aborted bad file descriptor

testing - 困惑为什么第 5.3 节中的测试会失败

ruby-on-rails - 用户使用carrierwave上传图像文件的适当s3权限