【问题标题】:How do I bypass validation rules set for a nested attribute in ruby on rails?如何绕过为 ruby​​ on rails 中的嵌套属性设置的验证规则?
【发布时间】:2012-05-12 00:21:36
【问题描述】:

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

它有一个验证规则“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

亲切的问候

【问题讨论】:

  • 这个问题有点误导。图片字段的验证无关紧要,如果未上传图片,您的微博条目应该只允许不允许从照片嵌套属性创建照片。 Adam 对 reject_if 的回答是一个很好的解决方案。

标签: ruby-on-rails ruby ruby-on-rails-3 rubygems ruby-on-rails-3.2


【解决方案1】:

有一个选项,: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']

这两个中的一个应该可以工作。

【讨论】:

  • 'micropost_image'是表单中文件输入标签的id,无关紧要。
  • 可能无关紧要,我在想属性,因为它们存在于块中,来自表单。而且我不确定 rails 是通过 id 标签还是 name 标签解析表单中的属性。最有可能是名称标签,尽管它可能是 id 标签。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
相关资源
最近更新 更多