首页 > 解决方案 > 模型关联问题

问题描述

目标是让商店创建奖励并将每个奖励与他选择的追随者相关联。这是我的设置:

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

我创建这个模型是为了捕捉奖励和追随者的关联。

class RewardParticipant < ApplicationRecord
  belongs_to :reward
  belongs_to :follow
end

我创建了以下迁移:

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

我无法确定这是否是模型关联和迁移的正确方法。我在这里先向您的帮助表示感谢!

标签: ruby-on-railsruby-on-rails-5

解决方案


一般来说,你是对的。

我们希望用户关注一家商店,而一家商店可以创造奖励,并为许多关注者提供许多奖励。

1. 视觉图式:

在此处输入图像描述

2.模型关联(完整版)

用户.rb

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

关注.rb

belongs_to :user
belongs_to :shop
has_many :reward_follows

商店.rb

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

奖励.rb

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

3. 不要使用日期字段。使用日期时间字段。

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

这为我个人节省了长期的工作时间。


推荐阅读