Specify an optional link in the Rails model

I have a Sponsor model and a promo code model.

  • Sponsor may have zero or more promotional codes.
  • An ad code can have sponsors zero or one .

Thus, the promotional code must have an optional link to the sponsor, that is sponsor_id, which may or may not matter. I am not sure how to install this in Rails.

Here is what I still have:

# app/models/sponsor.rb
class Sponsor < ActiveRecord::Base
  has_many :promo_codes  # Zero or more.
end

# app/models/promo_code.rb
class PromoCode < ActiveRecord::Base
  has_one :sponsor  # Zero or one.
end

# db/migrate/xxxxx_add_sponsor_reference_to_promo_codes.rb
# rails g migration AddSponsorReferenceToPromoCodes sponsor:references
# Running migration adds a sponsor_id field to promo_codes table.
class AddSponsorReferenceToPromoCodes < ActiveRecord::Migration
  def change
    add_reference :promo_codes, :sponsor, index: true
  end
end
It makes sense? I got the impression that I should use belongs_topromotional codes in my model, but I have no reason for this, I just have not seen an example has_manywith has_one.
+4
3

has_many :

# app/models/sponsor.rb
class Sponsor < ActiveRecord::Base
  has_many :promo_codes  # Zero or more.
end

# app/models/promo_code.rb
#table has sponsor_id field
class PromoCode < ActiveRecord::Base
  belongs_to :sponsor  # Zero or one.
end

has_one , has_many: .. has_many, "_to" "has_one" "_to". has_one : , has_many, has_one, .

+2

Rails 5 _to . , "optional":)

class User
  belongs_to :company, optional: true
end

: https://github.com/rails/rails/issues/18233

+30

, .

belongs_to , , @promo_code.sponsor , , @sponsor.promo_codes.

+1

All Articles