OSDN Git Service

t#30328:create op import ...and pull
[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         demander_artist = provider_artist.modify_artist providers_artist_attr
31         if demander_artist.valid?
32           provider_artist.attributes = {:provider_id => pid, :providers_artist_id => providers_artist_attr['id'], :demanders_artist_id => demander_artist.id}
33           unless provider_artist.save
34             res << providers_artist_attr
35           end
36         else
37           res << providers_artist_attr
38         end
39       end
40       raise ActiveRecord::Rollback if res.any?
41     end
42     res
43   end
44   
45 end