我有一个微帖子表单,允许用户上传照片并输入一些内容。图像文件字段是我的照片模型的嵌套属性。
它有一个验证规则“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
亲切的问候