Reputation: 61
The app I'm working on consist of users who can have multiple profiles each (it's supposed to be like a "family account"). When the users sign in, they can choose which profile they want to use.
I saved this information in a class variable but it doesn't work. If a user logs in from another browser or devise and chooses another profile, it's changed everywhere. The idea is to have different people accessing the same account and being able to choose different profiles, without it changing to the others.
I researched and found out it should be saved in a session but I don't know how to do it. I'd also like to know how can I modify it and how to access to it from controllers and / or views, if it's saved in a session.
A profile has: "user_id", the owner user of that profile, and "name", which is decided by the user when creating the profile.
I don't know if this is helpful, but I'm using the gem "Devise". If any other information is necessary, just let me know so I edit the post right away.
I'm sharing the code below so you can see what I've done so far:
application_controller.rb
@@current_profile = nil
def set_current_profile
@@current_profile = Profile.find(params[:id])
puts "#{@@current_profile.name}" # debug
end
def return_current_profile
return @@current_profile
end
profile_controller.rb
def set_current_profile
super
redirect_to main_main_page_path
end
def return_current_profile
super
end
helper_method :return_current_profile
profile_select.html.erb
<div class="container">
<div class="list-group col-md-4 offset-md-4" align="center">
<% @profiles.all.each do |profile| %>
<%= link_to profile.name, profile, method: :set_current_profile, class: "list-group-item list-group-item-action" %>
<% end %>
</div>
</div>
routes.rb
post 'profiles/:id', to: 'profiles#set_current_profile', as: :set_current_profile
Thank you in advance.
Upvotes: 1
Views: 143
Reputation: 68
In rails you can create new session and get the session like this:
# set the session
session[:key] = 'value'
# get the session
session[:key] #=> 'value'
If you want to save array in sessions, you can do like this:
# save the ids
session[:available_user_ids] = available_user_ids.join(',')
# get the ids
session[:available_user_ids].split(',') #> [1,2,3]
Upvotes: 2