ActiveRecord checks for models with has_many, owned by associations and STI

I have four models:

  • User
  • Reward
  • Icon
  • Gameweek

Associations are as follows:

  • The user has many rewards.
  • The premium belongs to the user.
  • The badge has many awards.
  • Bonus refers to the icon.
  • The user has many games.
  • GameWeek belongs to the user.
  • GameWeek has many rewards.
  • The prize belongs to the game_week.

Thus, user_id, badge_id and game_week_id are foreign keys in the reward table.

The icon implements an STI model. Let's say it has the following subclasses: BadgeA and BadgeB.

Some rules:

The game_week_id fk file may be zero for BadgeA, but may not be nil for BadgeB.

Here are my questions:

  • BadgeA, , ? , .
  • BadgeB, , ?
+3
1

:

, (, ):

http://yuml.me/6afcad62

:

:

class CreateAwards < ActiveRecord::Migration
  def self.up
    create_table :awards do |t|
      # custom attributes here
      t.string     :name
      t.text       :description
      t.references :user,       :null => false
      t.references :game_week#,  :null => false
      t.references :badge,      :null => false
      t.timestamps
    end
    # a user can be awarded no more than a badge per week
    add_index :awards, [:user_id, :badge_id, :game_week_id], :unique => true
    # a user can be awarded no more than a badge for ever
    #add_index :awards, [:user_id, :badge_id], :unique => true
  end

  def self.down
    drop_table :awards
  end
end

:

:

class Award < ActiveRecord::Base
  validate_uniqueness_of :user, :badge,
    :if => Proc.new { |award| award.badge === BadgeA }
  validate_uniqueness_of :user, :badge, game_week,
    :unless => Proc.new { |award| award.badge === BadgeA }
  #validate_uniqueness_of :user, :badge, game_week,
  #  :if => Proc.new { |award| award.badge === BadgeB }
end

:

, , :)

+1

Source: https://habr.com/ru/post/1746921/


All Articles