How to realize a share link function
If your app have many objects users want to share with other users, it may be time to think about a share link function. This article shows the way.
Specification
・User have lists about restaurants they like.
・User can create the link for sharing the list with other users(other users are not registered in this app).
・Other users can look at the list without logging in.
Preparation
class User
has_many :lists
end
and
class List
belongs_to :user
end
coding
Firstly, I created ShareHash object.
class ShareHash < ApplicationRecord belongs_to :list before_create :create_hash private def create_hash self.assign_attributes(hash_string: Digest::SHA1.hexdigest(Time.now.to_s)) endend
By create_hash, it becomes possible to create the share hash itself.
Secondly, it is necessary to remove user authentication when unregistered users reach the link.
class ApplicationController < ActionController::Base before_action :authenticate_user!, if: :authenticate?
private def authenticate?
true
endend
and
class SharedListsController < ApplicationController def show @list = ShareHash.find_by(hash_string: params[:hash_string]).list end private def authenticate?
false
endend
Users who are not unregistered can look at the contents of the list.
Finally, we have to set a creating share link button.
<%= link_to 'create the share link', list_share_hashes_path(@list), method: :post %>
It is possible to look at the list by putting the link into a browser.