OSDN Git Service

fix: fetch fail
[pettanr/pettanr.git] / app / models / provider_artist.rb
1 class ProviderArtist < ActiveRecord::Base
2   belongs_to :provider
3   belongs_to :artist, :foreign_key => :demanders_artist_id
4   
5   validates :provider_id, :presence => true, :numericality => true, :existence => true
6   validates :providers_artist_id, :presence => true, :numericality => true
7   validates :demanders_artist_id, :presence => true, :numericality => true
8   
9   def self.get_one pid, paid
10     ProviderArtist.find_by_provider_id_and_providers_artist_id(pid, paid) || ProviderArtist.new
11   end
12   
13   def modify_artist attr
14     ar = if self.artist
15       self.artist
16     else
17       Artist.new
18     end
19     ar.attributes = attr
20     ar.author_id = nil
21     ar.save
22     ar
23   end
24   
25   def self.import pid, providers_artists
26     res = []
27     ProviderArtist.transaction do
28       providers_artists.each do |providers_artist_attr|
29         provider_artist = ProviderArtist.get_one(pid, providers_artist_attr['id'])
30         paid = providers_artist_attr['id']
31         providers_artist_attr.delete 'id'
32         demander_artist = provider_artist.modify_artist providers_artist_attr
33         if demander_artist.valid?
34           provider_artist.attributes = {:provider_id => pid, :providers_artist_id => paid, :demanders_artist_id => demander_artist.id}
35           unless provider_artist.save
36             res << providers_artist_attr
37           end
38         else
39           res << providers_artist_attr
40         end
41       end
42       raise ActiveRecord::Rollback if res.any?
43     end
44     ArtistImportResult.new res
45   end
46   
47 end