2014-04-04 38 views
1

我正在向我的Rails應用中的用戶模型添加個人資料圖片。我已經成功地使用另一個模型獲得了截圖,但由於某些原因,我在配置文件圖片方面遇到了很多困難。爲了處理個人資料圖片,我創建了一個新的ProfilePics模式:Rails 3.2 +回形針:在用戶創建時分配默認圖像

class ProfilePic < ActiveRecord::Base 
    attr_accessible :image, :user_id 

    has_attached_file :profile_pic, :default_url => "/system/user_profile_pics/profile.png", 
            :url => "/system/user_profile_pics/:id/:basename.:extension", 
            :path => ':rails_root/public:url' 
            :styles => { :large => "800x400", :thumb => "36x36" } 

    # **** Associations **** 

    # State that each profile picture can have an associated user 
    belongs_to :users 

    # **** Validations **** 

    # Only allow the user to upload .bmp, .gif, .jpg, .jpeg, and .png files 
    validates_attachment_content_type :image, :content_type => /^image\/(bmp|gif|jpg|jpeg|png)/ 

    # Validate the presence of the user id 
    validates :user_id, :presence => true 

    # Order all profile pictures by ID, from first to last 
    default_scope :order => 'profile_pics.id ASC' 
end 

當用戶註冊時,他/她應該設置默認的配置文件圖片。這張圖片是在has_attached_file方法的default_url參數中指定的圖片文件。但是,我似乎無法弄清楚如何在用戶創建後爲用戶分配控制器中的默認配置文件圖片。我不想給資料圖片添加到註冊表單,如果我只是從控制器忽略它,我收到以下錯誤信息:

undefined method `before_image_post_process' 

我沒有作資料圖片要求關於用戶創建。我相信我已經建立了所有正確的數據庫表,但出於某種原因,我一直在收到這個錯誤。這是我嘗試在控制器分配用戶的默認資料圖片:

if @user.save 
    # Create a profile picture for the user 
    @user.profile_pic = ProfilePic.new(:image => nil, :user_id => @user.id) 

    ... 
end 

調試時,節省了用戶,在控制檯輸入「@ user.profile_pic」後,立即返回相同的「before_image_post_process」的錯誤。

有沒有人有任何關於這個問題的見解?非常感謝您提前!

+0

有'before_post_process'和'before_avatar_post_process'在回形針但像'before_image_post_process'沒有定義。你有什麼回形針?請附上完整的錯誤堆棧/跟蹤。 – pawel7318

+1

@ pawel7318'_ {{屬性} _post_process'用在'validations.rb'中,其中'屬性'是被驗證屬性的名稱。 –

回答

1

由於您將附加文件屬性定義爲profile_pic,但您正在對image屬性執行回形針驗證,所以出現此錯誤。

當您定義has_attached_file屬性時,Paperclip會自動創建一個<name>_post_process回調,稍後在驗證中使用它(其中是has_attached_file屬性的名稱)。

您創建了profile_pic_post_process但後來驗證正在尋找image_post_process,因此錯誤。

變化在ProfilePic模型您的驗證行:

# Only allow the user to upload .bmp, .gif, .jpg, .jpeg, and .png files 
    validates_attachment_content_type :profile_pic, :content_type => /^image\/(bmp|gif|jpg|jpeg|png)/ 
+1

謝謝大家的幫助!格雷姆的解決方案爲我工作。我決定將has_attached_file更改爲:image,而不是更改驗證,因爲我現在可以像這樣引用用戶的個人資料圖片:@ user.profile_pic.image。再次感謝! – Alexander

相關問題