驗證依賴於其他模型的活動記錄的模型值? - Validating an active record's model value that depends on other models? -开发者知识库

驗證依賴於其他模型的活動記錄的模型值? - Validating an active record's model value that depends on other models? -开发者知识库,第1张

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.

我想可靠地將值設置為(1 /類別數)。我希望這可以在category.build_weight,category.new,category.create等的情況下工作。我已經嘗試了上面的方法,以及使用觀察者,但它很脆弱。對不同建築方法的建議也表示贊賞。

Thanks, Justin

2 个解决方案

#1


2  

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

我將創建邏輯從ActiveRecord模型中提取到另一個類中。就像是:

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

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复