Allyl Isocyanate
Allyl Isocyanate

Reputation: 13626

Validating an active record's model value that depends on other models?

I have two models:

class Category < ActiveRecord::Base
  has_one :weight
  after_create :create_category_weight

  def create_category_weight
    self.weight = Weight.new :value => 1/Category.count
  end

end

and..

class Weight < ActiveRecord::Base
  belongs_to :category
  attr_accessible :value
end

I want to reliably set value to be (1/number of categories). I'd like this to work in the case of category.build_weight, category.new, category.create etc. I've tried the above approach, as well as using an observer, but its brittle. Suggestions on different architectural approaches also appreciated.

Thanks, Justin

Upvotes: 0

Views: 299

Answers (2)

th3mus1cman
th3mus1cman

Reputation: 406

I would extract the creation logic out of the ActiveRecord model and into another class. Something like:

class CategoryRepository

  def new_category
    @category = Category.new
    @category.weight = Weight.new(:value => (1 / Category.count))
    @category
  end

  def create_category(attributes)
    @category = Category.create(attributes)
    @category.weight = Weight.new(:value => (1 / Category.count))
    @category.save
    @category
  end

end

@repository = CategoryRepository.new

@category = @repository.new_category

@category = @repository.create_category(params[:category])

Upvotes: 2

David Sulc
David Sulc

Reputation: 25994

Why not use a before validation callback to set the weight, and validate the weight in the model? (If you do that, make sure you take race conditions into consideration...)

Upvotes: 1

Related Questions