0

我在驗證rails4應用程序中的模型中的圖像字段時出現問題。導軌/回形針對象創建問題

class ModelA < ActiveRecord::Base 
    validates :name, presence: true 
    validates :logo, presence: true 
    has_attached_file :logo, styles: { 
    thumb: '100x100>', 
    square: '200x200#' 
} 

在遷移中,將創建此模型的新實例。

def migrate(direction) 
    super 
    if direction == :up 
     obj = Model1.create!(:name => "Test") 

不指定所需的字段這是失敗,如果我明確地指定一個默認的圖像,然後將表沒有必要列呢。

如果我在遷移之前刪除圖像(在此例中是徽標)驗證,並且此後指定圖像文件和詳細信息(如其名稱),則會運行此遷移。 有沒有更好的方法來建立這個模型?

+1

請分享更多詳情。你想在這裏做什麼?可能是一個很好的例子。 –

+1

http://stackoverflow.com/questions/13122791/rails-validation-in-model-vs-migration?answertab=oldest#tab-top –

回答

0

我已經想通了。問題在於遷移 - 在遷移過程中,此對象創建之後添加了徽標遷移(以及驗證)。我將標識添加到Model1.create中!並移動此遷移經過這些遷移來解決錯誤。

因此,我粗略地遷移是:

def change 
    create_table :... do |t| 
    t.string :name 
    t.timestamps 
    end 

然後加入回形針列

def self.up 
    change_table :... do |t| 
    t.attachment :logo 
    end 
end 

,並在之後被他們未來的另一遷移添加的模型。

def migrate(direction) 
    super 
    if direction == :up 
    logo_img = File.open('app/assets/images/logo-big.png', 'rb') 
    Model1.create!(:name => "TestObj", :logo => logo_img)