Ruby on rails 创建默认曲别针图像并将其与Rails中的不同模型关联

Ruby on rails 创建默认曲别针图像并将其与Rails中的不同模型关联,ruby-on-rails,ruby,ruby-on-rails-4,paperclip,Ruby On Rails,Ruby,Ruby On Rails 4,Paperclip,在我的Rails应用程序中,我有两个模型:广告和图片,它们有很多/属于关系。我使用此设置可以将多张图片与一个广告关联 当用户通过表单自行添加图片时,一切正常,但如果他们不上传任何内容,我无法添加默认图片。在我的情况下,你会怎么做 这是我的广告模型: class Ad < ActiveRecord::Base belongs_to :municipality belongs_to :category belongs_to :user has_many :pictures,

在我的Rails应用程序中,我有两个模型:广告和图片,它们有很多/属于关系。我使用此设置可以将多张图片与一个广告关联

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

这是我的广告模型:

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
我想这可能有用:

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>

你期待什么?您没有在声明中提供有关要创建的图片的任何信息:@ad.pictures.create要使用默认图像,我必须提供哪些信息?我不会将默认图像保存在数据库中。如果没有任何图片,只需显示Picture.new即可。您可以在视图中执行此操作(可能过于凌乱),创建视图辅助对象,或者向Ad添加一个返回其图片或Picture.new的方法。
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>