Ruby on rails 模型关联的问题
目标是让商店创造奖励,并将每个奖励与他选择的追随者相关联。这是我的设置:Ruby on rails 模型关联的问题,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,目标是让商店创造奖励,并将每个奖励与他选择的追随者相关联。这是我的设置: 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
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-Shop
我创建这个模型是为了捕捉奖励和追随者的关联
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
class CreateRewards
我很难确定这是否是模型关联和迁移的正确方法。提前谢谢你的帮助 一般来说你是对的 我们希望用户关注一家店铺,而一家店铺可以创建奖励,并向许多追随者授予许多奖励 1.视觉模式: 2.模型关联(完整版本) 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
悬赏
has_many :reward_follows
belongs_to :shop
has_many :follows, through: :reward_follows
has_many :users, through: :follows
3.不要使用日期字段。使用日期时间字段。
理由:
这为我节省了长期的工作时间。接下来是什么?嘿@Gagan Gupta。。。这是给跟在商店后面的人的!可以您的设计还可以,但为什么需要关注RewardParticipant。您可以拥有用户和奖励,因为奖励已经属于特定的店铺,所以基本上您建议从
follow
和RewardParticipant
中删除关注关联,因为我可以使用用户
和查看
关联?删除内的follow关联,奖励\u参与者
,并将follow
替换为用户
,检查是否满足了您的所有要求?感谢帮助@Yshmarov.:)下面的奖励如何
模型关联。你忘了它们。我还认为这两个关联有很多:follows,through::raward\u follows
有很多:用户,through::follows
在奖励模型中是错误的<代码>奖励遵循只有所属的关联有很多:遵循,通过::奖励遵循
是一个基本的有很多通过
,其中奖励遵循
是一个简单的联合表。假设“user
通过user\u标签拥有许多标签”
“拥有许多:用户,通过::follows
——理论上看起来是合法的。值得一试。告诉我它在实践中是否有效!