There are two models: User ( has_many :shipments ) and Shipment ( belongs_to :user ). Everything works, seemingly normal, - user_id added to Shipment when it is created, but when added to the Shipment model, before_action :require_same_user representation of this model starts to before_action :require_same_user error:

undefined method `user 'for nil: NilClass

In the if current_user != @shipment.user line if current_user != @shipment.user , although @shipment.user specified in the create action. What do I misunderstand?

Shipment Controller:

 def create @shipment = Shipment.new(shipment_params) @shipment.user = current_user if @shipment.save redirect_to shipment_path(@shipment) else render 'new' end end def show @shipment = Shipment.find(params[:id]) end private def shipment_params params.require(:shipment).permit(:name, :adress, :user_id) end def require_same_user if current_user != @shipment.user flash[:alert] = "Доступ к данной директории ограничен." redirect_to root_path end end 

    1 answer 1

    You call the require_same_user() method before calling the create() and show() methods, so the @shipment is not initialized, since its value is set inside the create() and show() . Therefore, in the require_same_user() method, the @shipment variable is nil .

    Move the check inside the create() and show() methods after the @shipment value is available to @shipment .

    • 2
      ... or initialize the @shipment in an even earlier before_action . - D-side