开发者

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


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])


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...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜