OSDN Git Service

merge
[pettanr/pettanr.git] / app / models / user.rb
1 class User < ActiveRecord::Base
2   has_one :author
3   has_one :artist
4   
5   # Include default devise modules. Others available are:
6   # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
7   devise :database_authenticatable, :registerable,
8          :recoverable, :rememberable, :trackable,  :validatable, 
9          :omniauthable#, :confirmable
10
11   def create_token
12     loop do
13       token = Devise.friendly_token
14       if token_suitable?(token)
15         self.authentication_token = token
16         break
17       end
18     end
19     self.save
20   end
21
22   def token_suitable?(token)
23     !self.class.exists?(authentication_token: token)
24   end
25   
26   def delete_token
27     self.authentication_token = nil
28     self.save
29   end
30   
31   def destroy
32     res = false
33     User.transaction do
34       self.author.scrolls.each do |scroll|
35         raise ActiveRecord::Rollback unless scroll.destroy_with_scroll_panel
36       end
37       self.author.panels.each do |panel|
38         raise ActiveRecord::Rollback unless panel.destroy_with_elements
39       end
40       if self.artist
41         self.artist.original_pictures.each do |original_picture|
42           raise ActiveRecord::Rollback unless original_picture.destroy_with_resource_picture
43         end
44         raise ActiveRecord::Rollback unless self.artist.destroy
45       end
46       raise ActiveRecord::Rollback unless self.author.destroy
47       raise ActiveRecord::Rollback unless super
48       res = true
49     end
50     res
51   end
52   
53   private
54   def user_params
55     params.require(:user).permit(:email, :password, :password_confirmation, :remember_me, :authentication_token)
56   end
57   
58 end