2012-07-16 1 views
0

У меня есть приложение, прекрасно работающее на Heroku, и я пытаюсь подключить приложение к службе S3 Amazon с Carrierwave. Я думал, что у меня все файлы конфигурации работают на все, но я сталкиваюсь с проблемой, когда создаю экземпляр изображения. Я думаю, что это связано с Postgres и некоторыми его специфическими форматами и т. Д., Но вот главная проблема.Postgres + Heroku Ruby Creation

Я получаю TypeError (can't convert nil into String): на то, что похоже на POST в базу данных (в частности, на метод создания). Ошибка выглядит следующим образом:

app/controllers/pictures_controller.rb:62:in `create' 

TypeError (can't convert nil into String): 
POST xxxxxxxx.herokuapp.com/684-536-025/pictures dyno=web.1 queue=0 wait=0ms service=510ms status=500 bytes=643 

Вот начало процедуры POST, а также:

#<Picture id: nil, description: nil, image: nil, gallery_id: 15, gallery_url_id: "a432b35_21cc", original_filename: "Sunflower.gif", order_number: nil, created_at: nil, updated_at: nil> 

Я предполагаю, что проблема здесь в том, что Postgres не позволяет начать POST, когда есть поля это ноль. Как ни странно, sqlite отлично справляется с этим, поэтому я предполагаю, что проблема в Postgres и, к сожалению, я буду использовать Postgres для производства. Я не знаю достаточно о Postgres, чтобы действительно сузить эту проблему, поэтому я решил, что попрошу здесь посмотреть, смогу ли я получить какую-либо помощь/совет!

Спасибо!

EDIT: Вот метод создания дополнительной помощи

def create 
# Creates a picture class instance based on the json objects being passed in from 
# Carrierwave 
p_attr = params[:picture] 
p_attr[:image] = params[:picture][:image].first if params[:picture][:image].class == Array 

# Gets the gallery vai the uuid gallery url 
@gallery = Gallery.where(:url_id => params[:url_id]).first 
# Builds the picture based on the attributes passed in above from the json 
@picture = @gallery.pictures.build(p_attr) 
# Assigns the gallery_url_id attribute 
@picture.gallery_url_id = @gallery.url_id 

puts @picture.inspect 

# Handle the picture save according to success or not 
LINE 62 -> if @picture.save 
    respond_to do |format| 
    format.html { 
     # Calls the method in the model to format the json repsonse 
     render :json => [@picture.to_jq_upload].to_json, 
     :content_type => 'text/html', 
     :layout => false 
    } 
    format.json { 
     render :json => [@picture.to_jq_upload].to_json 
    } 
    end 
else 
    render :json => [{:error => "custom_failure"}], :status => 304 
end 

конец

Линия 62 отмечена в коде.

EDIT 2: Вот модель с просьбой ...

class Picture < ActiveRecord::Base 

    # The attributes accesible via an @picture 
    attr_accessible :gallery_id, :description, :image, :gallery_url_id, :original_filename, :order_number 
    belongs_to :gallery 

    # Attatches the carrierwave uploader to the picture class 
    mount_uploader :image, ImageUploader 

    # Referenced when each picture is created, the json is formatted as the following form 
    def to_jq_upload 
    { 
     "name" => read_attribute(:image), 
     "size" => image.size, 
     "url" => image.url, 
     "thumbnail_url" => image.thumb.url, 
     "delete_url" => id, 
     "picture_id" => id, 
     "delete_type" => "DELETE", 
     "url_id" => read_attribute(:gallery_url_id), 
     "original_filename" => read_attribute(:original_filename), 
     "order_number" => "" 
    } 
    end 

end 
+0

Что такое строка 62 в вашем контроллере изображений, а какое поле - ноль, вызывающее ошибку типа? app/controllers/pictures_controller.rb: 62: in 'create ' – bento

+0

Я собираюсь обновить сообщение с помощью метода create, видя, что это может помочь. Возможно, придется иметь дело с обнаружением атрибутов, хотя ... – user1470511

+0

Можем ли мы увидеть модель изображения, пожалуйста? – Andrei

ответ

0

Я закончил с использованием его в качестве конфигурации/initilizers/fog.rb

CarrierWave.configure do |config| 
    config.fog_credentials = { 
    :provider    => 'AWS', 
    :aws_access_key_id  => 'asdf', 
    :aws_secret_access_key => 'asdfadsf', 
    :region     => 'us-east-1' 
    } 
    config.fog_directory = 'modea-design-comp-viewer' 
end 

Кроме того, в контроллер I пришлось вручную установить два поля, которые были публикуемыми в ноле в базе данных в пустую строку, как например:

def create 
    # Creates a picture class instance based on the json objects being passed in from 
    # Carrierwave 
    p_attr = params[:picture] 
    p_attr[:image] = params[:picture][:image].first if params[:picture][:image].class == Array 

    # Gets the gallery vai the uuid gallery url 
    @gallery = Gallery.where(:url_id => params[:url_id]).first 
    # Builds the picture based on the attributes passed in above from the json 
    @picture = @gallery.pictures.build(p_attr) 
    # Assigns the gallery_url_id attribute 
    @picture.gallery_url_id = @gallery.url_id 

    @picture.order_number = "" 
    @picture.description = "" 

    # Handle the picture save according to success or not 
    if @picture.save 
     puts @picture.inspect 
     respond_to do |format| 
     format.html { 
      # Calls the method in the model to format the json repsonse 
      render :json => [@picture.to_jq_upload].to_json, 
      :content_type => 'text/html', 
      :layout => false 
     } 
     format.json { 
      render :json => [@picture.to_jq_upload].to_json 
     } 
     end 
    else 
     render :json => [{:error => "custom_failure"}], :status => 304 
    end 
    end 

Это сделало это для меня!