【问题标题】:Rails Associations - Associating a list of items with a particular user for a particular eventRails 关联 - 将项目列表与特定用户的特定事件相关联
【发布时间】:2018-09-24 14:34:09
【问题描述】:

我正在开发一个活动网站,用户可以在该网站的库存中拥有可以在他们的个人资料中列出的物品。为此,我正在使用:

has_many :items

在我的 user.rb 中。

然后,用户将能够参加任意数量的活动。对于每个事件,他们都会有一个唯一的项目列表,即要带到事件中的项目。我正在尝试找出关联以完成这项工作。

在 item_list.rb 中:

belongs_to :event
belongs_to :user
has_many :items

在 item.rb 中:

belongs_to :user
belongs_to :item_list

在 event.rb 中

has_many :item_lists

但令我困惑的是确保每个列表对于每个事件和用户都是唯一的。此外,我对item_list 的迁移是否会包含一系列项目?

任何见解将不胜感激。

【问题讨论】:

  • 你的意思是 我对 item_list 的迁移是否会包含一组项目?
  • 当我为 item_list 生成数据库迁移时,是否需要包含一列数组,即保存 item_ids

标签: ruby-on-rails associations


【解决方案1】:

但令我困惑的是确保每个列表都是独一无二的 事件和用户。

如果我没记错的话,您正在寻找带有scope 选项的validates_uniqueness_of

在您的item_list.rb 中,添加

validates_uniqueness_of :event_id, scope: :user_id

这将确保您拥有一个具有唯一 event_iduser_iditem_list。换句话说,每个item_list 对每个eventuser 都是唯一的。

当我为 item_list 生成数据库迁移时,我需要 包括一列数组,即保存 item_ids

不,Rails 会期望您在items 表中拥有item_list_id。因此,如果您想获取items 以获取item_list,您可以使用@item_list.items

【讨论】:

  • 谢谢,我想这主要是让我到达那里。我遇到了一个问题,当我尝试在将新项目添加到 item_list 之前创建新项目时,出现错误:“1 错误禁止保存此项目:Item_list 必须存在”。知道如何在创建 item_list 之前创建一个项目,以便稍后将其添加到 item_list 中吗?
  • 没关系,我实际上是通过更改我的 item.rb belongs_to 来解决的:item_list, optional: true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-13
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
相关资源
最近更新 更多