Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Setting default values for has_one association
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