Dev
Dev

Reputation: 467

Trouble with model associations

The goal is for a shop to create rewards and associate each reward to a follower of his choice. This is my setup:

class Shop < ApplicationRecord
  has_many :rewards
  has_many :follows
  has_many :users, through: :follows
end

class Reward < ApplicationRecord
  belongs_to :shop
end

class Follow < ApplicationRecord
  belongs_to :shop
  belongs_to :user
  has_many :reward_participant
end

class User < ApplicationRecord
  has_many :follows
  has_many :shops, through: :follows
end

I created this model in order to capture the reward and follower association.

class RewardParticipant < ApplicationRecord
  belongs_to :reward
  belongs_to :follow
end

And I have created the following migrations:

class CreateRewards < ActiveRecord::Migration[6.0]
  def change
    create_table :rewards do |t|
      t.string :title
      t.text :body
      t.date :expires
      t.integer :shope_id

      t.timestamps
    end
  end
end


class CreateRewardParticipants < ActiveRecord::Migration[6.0]
  def change
    create_table :reward_participants do |t|
      t.integer :reward_id
      t.integer :follow_id

      t.timestamps
    end
  end
end

I'm having trouble figuring out if this is the correct approach to the model associations and migrations. Thanks for the help in advance!

Upvotes: 4

Views: 107

Answers (1)

Yshmarov
Yshmarov

Reputation: 3729

Generally you are right.

We want users to follow a shop, and a shop can create rewards and grant many rewards to many followers.

1. Visual schema:

enter image description here

2. Model associations (complete version)

user.rb

has_many :follows
has_many :reward_follows, through: :follows
has_many :rewards, through: :reward_follows # NOT through shops
has_many :shops, through: :follows

follow.rb

belongs_to :user
belongs_to :shop
has_many :reward_follows

shop.rb

has_many :rewards
has_many :reward_follows, through: :rewards # NOT through follows
has_many :follows
has_many :users, through: :follows

reward.rb

has_many :reward_follows
belongs_to :shop
has_many :follows, through: :reward_follows
has_many :users, through: :follows

3. Do not use date field. Use datetime field.

Justification: https://www.ruby-forum.com/t/time-without-date/194146

This personally saved me hours of work long-term.

Upvotes: 4

Related Questions