What are good ways to get current user detail in m

2019-06-12 11:52发布

问题:

I used devise gem for authentication in my rails application. I want to get certain information about current user on after_create callback. How is it possible?
My model code is:

class Department
  field :name
  after_create :create_news
  private
  def create_news
    @user = current_user
  end
end

But when I create new department I get following error.

undefined local variable or method `current_user' for #<Department:0x00000005b51648>

What is the best way for this?

回答1:

Access control in rails is done at the controller level, not the model level. As a result, rails provides no mechanism for accessing the current user, cookies, etcetera, from inside model code. You can ferry the data into the model by parameters to methods, if you choose. However, that would be ignoring the design decisions of some of the best programmers in the industry, so I think it's probably not a good choice.

In other words, don't do what you're trying to do. Put the knowledge of how to do things in your model, but put controls around who can do them in the controller.

On the other hand, if you're trying to store the current user for some reason, then you should do that by some sort of association (or nested document, since you're using mongo). In that case, don't use current_user inside the model, but rather make an attr_accessor on user, set the user on the instance of your model to the current_user in the controller, and then save it how you need to in your callback.



回答2:

current_user is only available to controller and views. If your department model is connected to user model,you should add belong_to association and can do something like

after_create :create_news
def create_news
 @current_user = self.user
end