samedi 7 novembre 2015

FactoryGirl scoped has_one returning nil

I have the following models set up, and as you can see, Tenant has a has_one relationship to :current_rental_agreement which is a scoped has_one.

class Property < ActiveRecord::Base
  has_many :rental_agreements
  has_one :current_rental_agreement, -> { where("'#{ Date.today.to_s(:db) }' BETWEEN start_date AND end_date") }, class_name: 'RentalAgreement'
  has_one :tenant, through: :current_rental_agreement
end class

class Tenant < User
  has_many :rental_agreements
  has_many :properties, through: :rental_agreements
  has_one :current_rental_agreement, -> { where("current_date BETWEEN start_date AND end_date") }, class_name: 'RentalAgreement'
  has_one :property, through: :current_rental_agreement
end

class RentalAgreement < ActiveRecord::Base
  belongs_to :property
  belongs_to :tenant
end

This works in everything apart from the tests. Because this doesn't work in the tests, the has_one relationship to property obviously doesn't work.

I have the following Factories set up:

FactoryGirl.define do
  factory :agent do
    first_name "James"
    last_name "Smith"
  end

  factory :landlord do
    first_name "Bob"
    last_name "Builder"
  end

  factory :tenant do
    first_name "Jack"
    last_name "Builder"
  end
end

And I build them out like so:

agency = create(:agency)
agent = create(:agent, agency: agency)
landlord = create(:landlord, agency: agency)
property = create(:property, agency: agency, account_manager: agent, landlord: landlord)
tenant = create(:tenant, agency: agency)
rental_agreement = create(:rental_agreement, property: property, tenant: tenant, agent: agent) if agreement

When I run this however, it all appears fine.. they all return what they're meant to return, apart from when I call tenant.current_rental_agreement which returns nil, as does tenant.property. tenant.rental_agreements and tenant.properties work though.

It appears that although the rental_agreement record has been created, it doesn't seem to be linking up somehow, and I've no idea why!

Anyone have any ideas?

Aucun commentaire:

Enregistrer un commentaire