6

我懷疑問題在於我創建多態圖像屬性的方式。我在表格中使用fields_for。 在這種情況下,用戶可以創建帖子並使用回形針添加圖像,並使用S3存儲。 我使用的是多態圖像模式 「post_image」:配置Rails 3 +多態圖像模型+回形針和Amazon S3,沒有錯誤,但沒有上傳

class PostImage < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 
    #.merge(PAPERCLIP_OPS) 
    has_attached_file :image, :styles => { :medium => "200x200>", :thumb => "50x50>" }, 
          :storage => :s3, 
          :s3_credentials => "#{Rails.root}/config/s3.yml", 
          :path => "/:style/:id/:filename", 
          :bucket => "zounds-dev" 
    validates_attachment_presence :image 
    validates_attachment_size :image, :less_than => 5.megabytes 
end 

郵政型號:

class Post < ActiveRecord::Base 
    has_many :post_images, :as => :imageable, :dependent => :destroy 
    . 
    . 
    . 
    accepts_nested_attributes_for :post_images, :reject_if => lambda { |t| t[:post_image].nil?}, :allow_destroy => true 
end 

新話題形式:

=form_for(setup_post(@post,current_user), :html => { :multipart => true}) do |f| 
    %dl 
    =f.fields_for :post_images do |ff| 
     =ff.file_field :image 
    %dt.field=f.label :name 
    %dd.field=f.text_field :name 
    %dt.field=f.label :description 
    %dd.field=f.text_area :description 
    =f.fields_for :user do |u| 
     =render "user_fields", :f => u 
    =f.fields_for :assignments do |ff| 
     =ff.check_box :_destroy, {:checked => ff.object.persisted?}, '0','1' 
     =ff.label :_destroy, ff.object.group.name 
     =ff.hidden_field :group_id 
    .action=f.submit "Save Post" 

setup_post中郵form_for使用的輔助方法:(組東西不在這裏相關)

def setup_post(post, current_user) 
    groups = current_user.groups_as_owner + current_user.groups_as_member 
    (groups - post.groups).each do |group| 
     post.assignments.build(:group => group) 
    end 
    post.assignments.sort_by {|x| x.group.name } 
    post_image = post.post_images.build 
    post 
    end 

柱控制器:

def new 
    @user = User.find(params[:user_id]) 
    # @post = @user.posts.build 
    @post = Post.new 
    respond_to do |format| 
     format.html # new.html.erb 
     format.xml { render :xml => @post } 
    end 
    end 

def create 
    @user = current_user 
    @post = @user.posts.build(params[:post]) 
    . 
    . 
    . 
end 

我懷疑的問題是,我使用fields_for爲post_image屬性,但我已經看遍了,無法弄清楚實現多態嵌套圖像屬性的正確方法是什麼。

我也做了s3sh亞馬遜S3控制檯的事情,雖然我無法上傳圖像,因爲我無法弄清楚如何將正確的圖像路徑傳遞給open()函數,我連接到S3。我的s3.yml文件設置正確。

感謝亞勒, 布賴恩

回答

1

的問題是與reject_ifaccepts_nested_attributes爲Post模型

accepts_nested_attributes_for :post_images, :reject_if => lambda { |t| t[:post_image].nil?}, :allow_destroy => true

註釋掉它固定的問題。

+0

不錯的一個。感謝隊友:) – 2013-12-09 08:18:51

+0

以防萬一有人讀到這個:只刪除這個頁面:reject_if => lambda {| t | t [:post_image] .nil?}如果你想讓圖像記錄被刪除,你可以保留:allow_destroy => true。 – 2013-12-09 09:04:01

相關問題