0

我有一个微帖子表单,允许用户上传照片并输入一些内容。图像文件字段是我的照片模型的嵌套属性。

它有一个验证规则“presence => true”。微博不需要这样做。用户可以发布没有图片/照片的微博。

我如何为用户图片库使用相同的照片模型,并且在提交表单时需要一张照片,所以我无法禁用此规则。

当我发布微帖子表单时,有什么方法可以绕过我的照片模型中设置的验证规则?

控制器:

  def new
    @user = User.new 
    @micropost = Micropost.new(:user_id => users_id)
    @micropost.build_photo(:photo_album_id => current_user.photo_albums.find_by_album_title("microposts album").id)
  end

形式:

= form_for @micropost, :html => { :multipart => true }, :remote => true do |f|
    = f.fields_for :photo do |p|
        = p.hidden_field :photo_album_id
        = p.text_field :photo_title
        = p.file_field :image, :id => "micropost_image"
    = f.hidden_field :user_id
    = f.text_area :content
        = f.submit "Post"

微贴模型:

class Micropost < ActiveRecord::Base

    belongs_to :user
    has_many :comments, :dependent => :destroy 
    has_one  :photo, :dependent => :destroy


    accepts_nested_attributes_for :photo

    attr_accessor :username 
    attr_accessible :content, :user_id, :poster_id, :username, :remote_image_url, :photo_attributes

    validates :content, :presence => true, :length => { :maximum => 10000 }
    validates :user_id, :presence => true


end

照片模型:

class Photo < ActiveRecord::Base


    belongs_to :photo_album

    attr_accessible :photo_album_id, :photo_title, :image, :remote_image_url
    mount_uploader :image, ImageUploader

    alpha_num_non_word_char = /^[a-zA-Z0-9\D_ -]*$/

    validates :image, :presence => true
    validates :photo_title, :length => { :minimum => 2, :maximum => 50 },
                              :format => { :with => alpha_num_non_word_char,
                                           :message => "error"
                                         }, :if => :photo_title?    
    validate :picture_size_validation, :if => "image?"

    def picture_size_validation
    errors[:image] << "Your photo should be less than 1MB" if image.size > 1.megabytes
    end

end

亲切的问候

4

1 回答 1

2

有一个选项,:reject_if,你可以传递给accepts_nested_attributes_for,这样它就不会在某些条件下尝试创建新照片。它会像这样工作:

accepts_nested_attributes_for :photo, :reject_if => proc { |attributes| attributes['image'].blank? }

由于您将图像字段的 :id 指定为“micropost_image”,因此您可能必须像这样在 proc 中引用它:

attributes['micropost_image']

这两个之一应该工作。

于 2012-05-12T00:42:01.767 回答