【问题标题】:Trouble with model associations模型关联问题
【发布时间】:2021-02-02 10:30:12
【问题描述】:

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

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

我无法确定这是否是模型关联和迁移的正确方法。提前感谢您的帮助!

【问题讨论】:

  • Follow over here 是什么?
  • 嘿@Gagan Gupta...这是给关注商店的人的!
  • 好吧,你的设计还行,但是为什么需要在RewardParticipant中关注。你可以有用户和奖励,因为奖励已经属于特定的商店
  • 所以基本上你建议从Follow 和RewardParticipant 中删除关注关联,因为我可以使用User 和Review 关联?
  • 移除reward_participants中的关注关联,将follow替换为user,并检查您的所有要求是否得到满足?

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


【解决方案1】:

一般来说你是对的。

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

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

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。不要使用日期字段。使用日期时间字段。

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

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

【讨论】:

  • 感谢@Yshmarov 的帮助。 :)))) reward_follows 模型关联怎么样。你忘了他们。
  • 另外我觉得奖励模型里面has_many :follows, through: : reward_followshas_many :users, through: :follows这两个关联是错误的!!!
  • reward_follows 仅有 belongs_to 关联
  • has_many :follows, through: : reward_follows 是一个基本的has many through,其中reward_follows 是一个简单的联合表。想象一下“user 有很多 tags 到 user_tags”
  • has_many :users, through: :follows - 理论上看起来是合法的。值得尝试。告诉我它在实践中是否有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多