WebQube
WebQube

Reputation: 8991

Rails ActiveRecord type constraint

I have the following model in a rails App class Banking::PaymentToken < Banking::Token (which is ActiveRecord)

Banking::PaymentToken.find() include the following SQL constraint?

"WHERE payment_tokens.type IN ('Banking::PaymentToken')"

I want to add constraints "WHERE payment_tokens.type IN ('Banking::PaymentToken', 'other_type')"

Upvotes: 1

Views: 68

Answers (3)

Lital Zubery
Lital Zubery

Reputation: 36

Thats how ActiveRecord implements inheritance.

Banking::Token < ActiveRecord::Base is the base class working against payment_tokens table (all records). Which means any select from BankingToken will filter against all the records in payment_tokens table.

Banking::PaymentToken < Banking::Token inherits from Banking::Token which means it works against the same table but filters by default only type = "Banking::PaymentToken", (type is the default inheritance_column for Active Record)

You wish to create a new class which inherits from Banking::PaymentToken, lets say: Banking:OtherToken < Banking::PaymentToken As the mechanism works it will filter by default type in ("Banking:OtherToken").

Now Banking::PaymentToken filter by default will be: type in ("Banking::PaymentToken", "Banking:OtherToken") because every OtherToken is a PaymentToken as well..

Upvotes: 2

WebQube
WebQube

Reputation: 8991

Figured it out: I need to create the other part to inherit form PaymentToken Banking::OtherToken < Banking::PaymentToken

That will give me the desired query.

Upvotes: 0

zdk
zdk

Reputation: 1576

I think this

Banking::PaymentToken.find_by(type: 'Banking::PaymentToken', 'other_type')

should be translated to the equivalent SQL you want.

Bear in mind that type column is restricted word. Therefore, you have to know what you are doing when using this column name.

Upvotes: 0

Related Questions