验证空的nestet属性

时间:2016-03-28 09:43:06

标签: ruby-on-rails

我的模型BlogPost具有嵌套属性Poll。

class BlogPost < ActiveRecord::Base
  # attr_accessible :subject, :body, :tag_list, :commentable_by, :visible_by, :attachments_attributes
  include ActiveModel::ForbiddenAttributesProtection

  belongs_to :user
  has_many :comments, as: :owner, dependent: :destroy
  has_many :attachments, as: :owner, dependent: :destroy
  has_many :photos, through: :attachments, source: :asset, source_type: 'Photo'
  has_many :videos, through: :attachments, source: :asset, source_type: 'Video'
  belongs_to :article
  has_many :blog_post_subscriptions, dependent: :destroy
  has_many :subscribers, through: :blog_post_subscriptions, class_name: 'User', source: :user
  has_one  :poll, as: :owner, dependent: :destroy
  has_many :poll_items, dependent: :destroy

  accepts_nested_attributes_for :attachments, :allow_destroy => true
  accepts_nested_attributes_for :poll, allow_destroy: true,
                                    reject_if: proc { |attributes| attributes['question'].blank? }
  accepts_nested_attributes_for :poll_items, allow_destroy: true, 
                                reject_if: proc { |attributes| attributes['answer'].blank? }                                  

  validates :user, :subject, :presence => true
  validates :body, presence: true, if: :body_required?
  validates :body, length: { maximum: 65000 }
  validate :validate_duplicate, on: :create


  before_create :check_paid_attributes
  after_create :set_last_comment_at
  before_save :set_tags_line

Model Poll具有嵌套属性poll_items:

# == Schema Information
#
# Table name: polls
#
#  id             :integer          not null, primary key
#  question       :string(255)
#  results_hidden :integer
#  from_date      :datetime
#  to_date        :datetime
#  owner_id       :integer
#  owner_type     :string(255)
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#
# Indexes
#
#  index_polls_on_owner_id  (owner_id)
#

class Poll < ActiveRecord::Base
  POLL_ITEMS_COUNT_MAX = 5
  attr_accessible :from_date, :question, :results_hidden, :to_date, :owner_id, :poll_items_attributes

  belongs_to :owner, polymorphic: true
  has_many :poll_items, dependent: :destroy
  has_many :poll_votes, through: :poll_items

  accepts_nested_attributes_for :poll_items, allow_destroy: true, 
                                reject_if: proc { |attributes| attributes['answer'].blank? }

  #validates :owner, :question, :from_date, :to_date, presence: true
  #validate :validate_duplicate, on: :create
  #validate :validate_max_poll_items
  validates :poll_items, association_count: { maximum: POLL_ITEMS_COUNT_MAX }
  validates :question, :from_date, :to_date, presence: true 

模型民意调查:

# == Schema Information
#
# Table name: poll_items
#
#  id               :integer          not null, primary key
#  answer           :string(255)
#  poll_votes_count :integer
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#  post_id          :integer
#  blog_post_id     :integer
#  poll_id          :integer
#  sequence         :integer
#
# Indexes
#
#  index_poll_items_on_blog_post_id  (blog_post_id)
#  index_poll_items_on_poll_id       (poll_id)
#  index_poll_items_on_post_id       (post_id)
#

class PollItem < ActiveRecord::Base
  attr_accessible :answer
  attr_readonly :poll_votes_count

  belongs_to :poll
  belongs_to :post
  has_many :poll_votes, dependent: :destroy
  has_many :users, through: :poll_votes

  validates :answer, presence: true
  #validate :validate_duplicate, on: :create

  #validates_uniqueness_of :answer, scope: :poll

  scope :editable, lambda { |u|
    unless u.moderator?
      where(:poll.owner.user_id => u.id).where(:created_at.gt Settings.edit_delay.minutes.ago)
    end
  }

  #before_validation do
    #binding.pry
    #self.poll = poll if poll
  #end


  private
  def validate_duplicate
    errors.add(:base, :duplicate) unless poll.poll_items.where(answer: answer).empty?
  end
end

blog_posts_controller.rb

def new
    @post = current_user.blog_posts.new
    @poll = @post.build_poll
    @poll.poll_items.build
  end

  def create
    params[:blog_post][:draft] = params[:draft].present?
    @post = current_user.blog_posts.create(blog_post_params)

    redirect_to @post, notice: (@post.draft? ? 'Черновик сохранен' : 'Пост опубликован')
  rescue ActiveRecord::RecordInvalid
    flash[:error] = ":("
    render :new
  end

我正在创建一个包含民意调查的新博文。如果我没有指定答案(模型PollItem),则仍会创建poll。为什么呢?

有必要在空答案选项中未创建投票,并且显示错误。

1 个答案:

答案 0 :(得分:1)

验证BlogPost&amp;的最小和最大关联数。 PollItem将以下验证代码添加到两个模型中:

validates :poll_items, association_count: {minimum: 1, maximum: POLL_ITEMS_COUNT_MAX }