E69ea2d40777aad638a6b85041f76140

I need to check the nested model before publication

class Round < ActiveRecord::Base
  belongs_to :season
  has_many :questions, :dependent => :destroy do
  	def not_valid
  	  self.select do |question|
  	  	!question.valid?
  	  end
  	end
  end
end
class Question < ActiveRecord::Base

  belongs_to :round
  
  validates_presence_of :name
  validates_presence_of :body, :on => :update
  
end
class RoundsController < ApplicationController
  def publish
  	@round = @season.rounds.find(params[:id])
  	if @round.valid? && @round.questions.not_valid.empty? && @round.update_attribute(:published, true)
  	  flash[:notice] = 'Round was successfully published.'  	  	  
	end
  	redirect_to season_round_path(@round.season, @round)	
  end
end

Refactorings

No refactoring yet !

Be1e3ee645d23c95ba650c21bc885927

Fabien Jakimowicz

March 24, 2009, March 24, 2009 12:42, permalink

No rating. Login to rate!

I'm not sure why you need to manually validate each questions since ActiveRecord should validate them before saving.

Anyway, here is a better way to do it.

class Round < ActiveRecord::Base
  belongs_to :season
  has_many :questions, :dependent => :destroy

  def validate
    errors.add("questions", "are invalid") unless questions.all? {|q| q.valid?}
  end
end
class Question < ActiveRecord::Base
  belongs_to :round
end
class RoundsController < ApplicationController
  def publish
    @round = @season.rounds.find(params[:id])
    @round.update_attributes! :published => true
    flash[:notice] = 'Round was successfully published.'
  rescue ActiveRecord::RecordInvalid
    flash[:notice] = 'Round has invalid questions.'
  ensure
    redirect_to season_round_path(@round.season, @round)
  end
end
E69ea2d40777aad638a6b85041f76140

Pavel Druzyak

March 24, 2009, March 24, 2009 13:25, permalink

No rating. Login to rate!

Sorry, I forgot about the model of question.
Because when we try to publish the round(only when publish), all the questions in this round should have the title and body. Validate presence of body question only on updating it.

class Question < ActiveRecord::Base

  belongs_to :round
  
  validates_presence_of :name
  validates_presence_of :body, :on => :update
  
end

Your refactoring





Format Copy from initial code

or Cancel