我正在尝试将product
模型与具有倍数条件的transaction
模型相关联。 transaction
模型包含product_id
,user_id
,borrowing_date
和return_date
。
我想指定他们previous_transactions
和next_transactions
之间的两种关系:
previous_transactions
由borrowing_date
和return_date
定义为零。next_transactions
由borrowing_date
和return_date
定义为零。我尝试了以下代码,但它不起作用:
class Product
.
.
.
has_many :transactions
has_many :previous_transactions, -> { where return_date: !nil, borrowing_date: !nil },
class_name:'交易' has_many:next_transactions, - > {where borrowing_date:nil,return_date:nil},class_name:'Transaction' 。 。 。 端
这是我的测试:
describe Product do
let(:owner) { FactoryGirl.create(:user) }
before { @product = owner.owned_products.new(name: "Marteau") }
subject { @product }
describe "previous_transactions" do
let(:user) { FactoryGirl.create(:user) }
before { Transaction.create(product: @product, seeker: user, borrowing_date: 1.day.ago, return_date: 1.hour.ago) }
its(:previous_borrowers) { should include(user) }
end
end
这里出现错误信息:
1) Product previous_transactions previous_borrowers
Failure/Error: its(:previous_borrowers) { should include(user) }
expected #<ActiveRecord::Associations::CollectionProxy []> to include #<User id: 32, name: "Robot 12", email: "numero12@robots.com", password_digest: "$2a$04$hM7vB0LEpKiIXVVjrOLEEOPMLP5MXzkphP7WKrakvP1a...", remember_token: "czFAoOHWBhHRT6OyvohrUw", admin: false, created_at: "2013-06-12 12:24:56", updated_at: "2013-06-12 12:24:56">
Diff:
@@ -1,2 +1,2 @@
-[#<User id: 32, name: "Robot 12", email: "numero12@robots.com", password_digest: "$2a$04$hM7vB0LEpKiIXVVjrOLEEOPMLP5MXzkphP7WKrakvP1a...", remember_token: "czFAoOHWBhHRT6OyvohrUw", admin: false, created_at: "2013-06-12 12:24:56", updated_at: "2013-06-12 12:24:56">]
我想我必须改变{ where return_date: !nil, borrowing_date: !nil }
,但我找不到。我尝试了以下方法,但它也不起作用:
{ where :return_date =! nil && :borrowing_date =! nil }
{ where :return_date.present? && :borrowing_date.present? }
{ where return_date: true, borrowing_date: true } # Because if nil? is false, something not nil must be true ?
有人告诉我there使用像return_date IS NOT NULL
这样的SQL语法,但这依赖于数据库。所以我想找点别的......