创建默认的Paperclip图像并将其与Rails中的不同模型相关联

时间:2015-02-17 15:34:44

标签: ruby-on-rails ruby ruby-on-rails-4 paperclip

在我的Rails应用程序中,我有两个模型:Ad和Picture with has_many / belongs_to relationship。我使用此设置可以将许多图片与一个广告相关联。

当用户通过表单自己添加图片时,一切正常,但我无法添加默认图片以防他们不上传任何内容。在我的情况下你会怎么做?

这是我的广告模型:

class Ad < ActiveRecord::Base

  belongs_to :municipality
  belongs_to :category
  belongs_to :user
  has_many :pictures, dependent: :destroy

  validates :title, presence: true, length: { in: 5..150 }
  validates :description, presence: true, length: { in: 60..2500 }
  validates :municipality_id, presence: true
  validates :category_id, presence: true, numericality: { only_integer: true }

  def self.search(query)
    if Rails.env.development?
      where("title like ?", "%#{query}%")
    else
      # Case insensitive search for PostgreSQL
      where("title ilike ?", "%#{query}%")
    end
  end

end

这是我的带有Paperclip配置的图片模型:

class Picture < ActiveRecord::Base
  belongs_to :ad
  has_attached_file :pic, styles: { medium: "300x300>", big: "1000x1000>" }, default_url: "/images/default.png"
  validates_attachment_content_type :pic, content_type: /\Aimage\/.*\Z/
end

这是我的广告控制器的创建操作:

def create
  @ad = current_user.ads.new(ad_params)
  if @ad.save
    params[:pictures].each { |pic| @ad.pictures.create(pic: pic) } if params[:pictures]
    flash[:success] = "Die Anzeige wurde erfolgreich erstellt!"
    redirect_to @ad
  else
    render action: :new
  end
end

我认为这可行:

def create
  @ad = current_user.ads.new(ad_params)
  if @ad.save
    if params[:pictures]
      params[:pictures].each { |pic| @ad.pictures.create(pic: pic) }
    else
      @ad.pictures.create # Add default image to @ad
    end
    flash[:success] = "Die Anzeige wurde erfolgreich erstellt!"
    redirect_to @ad
  else
    render action: :new
  end
end

但这是结果:

#<Picture id: 64, pic_file_name: nil, pic_content_type: nil, pic_file_size: nil, pic_updated_at: nil, created_at: "2015-02-17 15:23:03", updated_at: "2015-02-17 15:23:03", ad_id: 52>

0 个答案:

没有答案