0

我正在使用 Ruby on Rails 3.2.2,我想知道以下代码具有或可能具有的优点/缺点:

class ApplicationController < ActionController::Base
  before_filter :set_current_user_for_models

  private

  def set_current_user_for_models
    User.current_user = User.find(...) # Find the user from cookies.
  end
end

class User < ActiveRecord::Base
  attr_accessible :current_user

  private

  def some_method(user)
    if User.current_user == user
      # Make a thing...
    else
      # Make another thing...
    end
  end
end

class Article < ActiveRecord::Base
  def some_method(user)
    if User.current_user == user
      # Make a thing...
    else
      # Make another thing...
    end
  end
end

你有什么建议吗?您将如何改进代码?

在@tokland 对@Wawa Loo 答案的评论后更新

注意:主要区别在于User.current_user应该在after_find, after_create,...模型回调中更新。像这样的东西:

class User < ActiveRecord::Base
  attr_accessible :current_user

  after_initialize :some_method

  private

  def some_method
    if User.current_user == self
      # Make a thing...
    else
      # Make another thing...
    end
  end
end

class Article < ActiveRecord::Base
  after_destroy :some_method

  private

  def some_method
    if User.current_user == self.user
      # Make a thing...
    else
      # Make another thing...
    end
  end
end
4

2 回答 2

0

你的代码看起来不错。我建议您通读此 Rails 样式指南,以了解 Rails 开发的概述。

于 2012-06-20T09:11:07.887 回答
0

我建议将 存储current_user在您的 中session,而不是作为 User 类的访问器。该方法set_current_user_for_models将随每个请求一起执行。无论如何它如何找到用户 - User.find(...)

于 2012-06-20T09:16:48.713 回答