ruby-on-rails - 模型关联问题
问题描述
目标是让商店创建奖励并将每个奖励与他选择的追随者相关联。这是我的设置:
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
我无法确定这是否是模型关联和迁移的正确方法。我在这里先向您的帮助表示感谢!
解决方案
一般来说,你是对的。
我们希望用户关注一家商店,而一家商店可以创造奖励,并为许多关注者提供许多奖励。
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
这为我个人节省了长期的工作时间。
推荐阅读
- r - 计算每天到午夜的时差
- hyperlink - 微信微信链接如何转化为二维码
- python - 在 Python 中使用虚拟助手并遇到 pip 模块问题
- spring - Sping 启动不运行
- python - Python3:dict 构造函数会创建深层副本吗?
- android - Android - 电话选择器(HintRequest)未在所有设备中提供电话号码建议
- python - 安装 fastai 和 boto3 后 Python 不起作用。权限被拒绝 // 未找到 Python
- java - 是否可以使用 java 在 ldap 中更改用户的基本 dn?
- javascript - 如何返回按特定偏移量移动的小时:分钟字符串?
- css - 引导一列宽但仅在大屏幕上