Rails3 has_many belongs_to范围连接合并不起作用

时间:2012-10-11 17:27:46

标签: ruby-on-rails-3 join merge scope rspec2

我在Rails 3.2上,Ruby 1.9.2我正在尝试使用范围连接/合并语法来保持我的模型逻辑干燥。我在测试这个时遇到了麻烦,我不知道为什么。

product.rb:

belongs_to :product_status

scope :sellable, -> {joins(:product_status).where('products.quantity_available > 0').merge(ProductStatus.sellable)}

product_status.rb:

has_many :products

scope :sellable, -> {where("product_statuses.name in ('Active','Deactivated')")}

在我的测试中,测试产品状态通过:

it "should return 0 count without a valid member" do
  FactoryGirl.create(:product_status)
  ProductStatus.sellable.count.should == 0
end

it "should return 1 count with a valid member" do
  FactoryGirl.create(:active_product_status)
  ProductStatus.sellable.count.should == 1
end

但我无法通过我的产品测试:

it "should return 1 count with a valid member" do
  active_product_status = FactoryGirl.create(:active_product_status)
  FactoryGirl.create(:product, :product_status => active_product_status)
  Product.sellable.count.should == 1
end

产品的数量设置为大于0.我已经写了一个不同的范围来测试那个部分,它没有通过任何问题。

通过调用创建的SQL看起来对我来说是正确的,但也许它会更好地向这样的人展示问题:

SELECT COUNT(*) FROM `products` INNER JOIN `product_statuses` ON `product_statuses`.`id` = `products`.`product_status_id` WHERE products.quantity_available > 0 AND (product_statuses.name in ('Active','Deactivated'))

我在测试中添加了以确保active_product_status实际上是可销售的

it "should return 1 count with a valid member" do
  active_product_status = FactoryGirl.create(:active_product_status)
  product = FactoryGirl.create(:product, :product_status => active_product_status)
  ProductStatus.sellable.all.include?(product.product_status).should == true
  Product.sellable.count.should == 1
end

ProductStatus测试通过,而不是产品测试。

我之前从未使用过连接/合并语法,所以我不确定我是否遗漏了某些内容。如果我从以下地方打电话,我可以让它发挥作用:

ProductStatus.sellable.joins(:products).merge(Product.sellable)

但我需要能够从产品型号进行此调用。任何帮助将不胜感激。

0 个答案:

没有答案
相关问题