where's the appropriate place to handle writing the current_user.id to an object

青春壹個敷衍的年華 提交于 2019-12-25 06:53:03

问题


I am not using Devise but have implemented a simple authentication scheme (basically outlined here http://railscasts.com/episodes/250-authentication-from-scratch) with the relevant part being here:

application_controller.rb

helper_method :current_user

private
def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

I have a list of assets that a user must be authorized to add. I am using paperclip. A user can has_many and a asset belongs_to a user (although this is essentially irrelevant to where it is assigned since my asset model is polymorphic for different assetable_types).

Where should I assign the current_user id to an asset? I would think in the model; maybe I should do a default_values using the session[:user_id] but that seems to be kinda ugly.

Also, these are nested_attributes and the models that these are nested to, currently don't know anything about the user. So really the source of information for the current_user isn't part of the current association.

thx

edit 1 should I create an instance of a User based upon the session[:user_id] value or just push it in?


回答1:


If I understand your question correctly, why not assign the user to the asset in whichever controller first finds out that the asset belongs to the user? It's the controller's responsibility to translate web requests (including the session / current user) into something applicable to the model.



来源:https://stackoverflow.com/questions/9404064/wheres-the-appropriate-place-to-handle-writing-the-current-user-id-to-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!