SORRROW
SORRROW

Reputation: 55

Rails 4 has_one through with where clause

I am trying to establish a direct relation via has_one between two models, Client and Address as in has_one :billing_address but Client doesn't have a direct relation to Address, Contact does, the models:

Client

class Client < ActiveRecord::Base
 belongs_to :contact
 accepts_nested_attributes_for :contact
end

Contact

class Contact < ActiveRecord::Base
 has_one :client

 has_many :addresses, dependent: :destroy
 accepts_nested_attributes_for :addresses, allow_destroy: true
end

Address

class Address < ActiveRecord::Base
 belongs_to :contact

 enum kind: [:address, :shipping, :billing]
end

So what I want is to to be able to do Client.shipping_address or Client.billing_address, the enum in the Address model is what will allow the query. The reason behind that is because the Contact of Client will have two address records, one for billing and one for shipping and I want quick access via relations

I tried in the Client model:

has_one(:billing_address, -> { where(kind: :billing) }, class_name: Address, through: :contact)

But when in the view I o:

client.billing_address

I get a undefined method to_sym' for nil:NilClass And I can't seem to resolve it, thanks.

Upvotes: 1

Views: 7197

Answers (1)

deefour
deefour

Reputation: 35360

You need to specify the :source on the association since it cannot be inferred.

has_one :billing_address, through :contact, source: :addresses, -> { where(kind: :billing) }

Without :source, it's going to look for a :billing_address association on the Contact model.

Source


Update

After reading up on the enum docs, it looks like you may need to modify the scope, referencing the mapping directly:

-> { where(kind: Address.kinds[:billing]) }

I believe this is because the :kind field in the database is expected to be type INTEGER.

Upvotes: 1

Related Questions