I'm creating a to-do list app and I want users to be able to create a list without logging in and only log in when they wish to save their list. Right now I'm using Devise, where I created a belongs_to association of the activity to the user. The save works if the user is logged in but not otherwise.
How can I allow users to add activities to the activities index without having them being logged in and have the activities be deleted on refresh unless they log in and save them?
Activities_Controller:
def create
@activity = Activity.new(activity_params)
authorize @activity
if user_signed_in?
@activity.user = current_user
if @activity.save
redirect_to activities_path
else
render :new
end
else
@activity = Activity.new(activity_params)
if @activity.save
redirect_to activities_path
else
render :new
end
end
end
CodePudding user response:
before_action :authenticate_user!, except: [:new]
try this
CodePudding user response:
You could create a additional Policy that will not check for users.
# app/policies/not_mandatory_user_application_policy.rb
class NotMandatoryUserApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
# raise Pundit::NotAuthorizedError unless user
@user = user
@record = record.is_a?(Array) ? record.last : record
end
# ...
end
# app/policies/activity_policy.rb
class ActivityPolicy < NotMandatoryUserApplicationPolicy
def new?
true
end
# ...
end
This way you can distinguish between the policies from which you inherit whether a user must be present or not. With this way, the verification in the controllers remains the same.
