OSDN Git Service

t#30328:pull porting
[pettanr/pettanr.git] / app / models / provider_artist.rb
diff --git a/app/models/provider_artist.rb b/app/models/provider_artist.rb
new file mode 100644 (file)
index 0000000..5f9806b
--- /dev/null
@@ -0,0 +1,47 @@
+class ProviderArtist < ActiveRecord::Base
+  belongs_to :provider
+  belongs_to :artist, :foreign_key => :demanders_artist_id
+  
+  validates :provider_id, :presence => true, :numericality => true, :existence => true
+  validates :providers_artist_id, :presence => true, :numericality => true
+  validates :demanders_artist_id, :presence => true, :numericality => true
+  
+  def self.get_one pid, paid
+    ProviderArtist.find_by_provider_id_and_providers_artist_id(pid, paid) || ProviderArtist.new
+  end
+  
+  def modify_artist attr
+    ar = if self.artist
+      self.artist
+    else
+      Artist.new
+    end
+    ar.attributes = attr
+    ar.author_id = nil
+    ar.save
+    ar
+  end
+  
+  def self.import pid, providers_artists
+    res = []
+    ProviderArtist.transaction do
+      providers_artists.each do |providers_artist_attr|
+        provider_artist = ProviderArtist.get_one(pid, providers_artist_attr['id'])
+        paid = providers_artist_attr['id']
+        providers_artist_attr.delete 'id'
+        demander_artist = provider_artist.modify_artist providers_artist_attr
+        if demander_artist.valid?
+          provider_artist.attributes = {:provider_id => pid, :providers_artist_id => paid, :demanders_artist_id => demander_artist.id}
+          unless provider_artist.save
+            res << providers_artist_attr
+          end
+        else
+          res << providers_artist_attr
+        end
+      end
+      raise ActiveRecord::Rollback if res.any?
+    end
+    res
+  end
+  
+end