Setting default values for has_one association
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
# Adding the subscription association and set | |
# the desired kind of the subscription | |
has_one :subscription, -> {where kind: Subscription.kinds[:single]} | |
end | |
class Subscription < ActiveRecord::Base | |
# Adding an enum with predefined values | |
enum kind: {single: 2, company: 7} | |
belongs_to :user | |
end | |
# Testing the assocation | |
# After building a subscription the kind will | |
# be preset to 2 | |
@user = User.new | |
@user.build_subscription | |
=> #<Subscription id: nil, user_id: nil, kind: 2, name: nil, note: nil, created_at: nil, updated_at: nil> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a good way to set default values for
has_one
associationBut, for a business use case?
Pros:
Cons:
single
orcompany
subscription (but, it may be the required business logic)if
sinclude
Alternate solution is STI
SingleSubscription < Subscription
CompanySubscription < Subscription
Pros:
Cons:
Just my opinion. Discardable at your free will😀
Have a wonderful year ahead. (Despite the pandemic, Yes)