【发布时间】:2021-07-06 08:55:12
【问题描述】:
我是 Rails 的新手,正在开发一个应用程序,该应用程序允许用户创建一个 List,其中包含他们在某个类别中排名前 5 位的 Items。我遇到的主要问题是如何跟踪List 订单(应该允许更改,并且每个User 都会有所不同)?
我的Items 可以属于许多Lists,我的Lists 应该有许多Items 所以,截至目前,我使用has_and_belongs_to_many 关联我的Item 和List 模特。
我现在跟踪列表顺序的想法是让我的@list 有 5 个属性:列表中的每个排名都有一个(即:first, :second, :third, :fourth, :fifth),我正在尝试关联@item 实例到@list 属性(即@list.first = @item1, @list.second = @item2 等...)。现在我将@list 属性保存到@item ID (@list.first = 1),但我更希望能够调用方法.first 或.second 等并直接在特定@ 987654341@实例。
这是我当前的 lists、items 架构和 has_and_belongs_to_many 关联所需的连接表 list_nominations - 我很确定我没有正确使用(:points 中的属性items 将成为跟踪 item 受欢迎程度的一种方式:
create_table "lists", force: :cascade do |t|
t.integer "user_id"
t.integer "category_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "first"
t.string "second"
t.string "third"
t.string "fourth"
t.string "fifth"
end
create_table "items", force: :cascade do |t|
t.string "name"
t.integer "category_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "points", default: 0
end
这是我的List 和Item 模型中的代码:
class List < ApplicationRecord
belongs_to :user
belongs_to :category
has_and_belongs_to_many :items
end
class Item < ApplicationRecord
belongs_to :category
has_and_belongs_to_many :lists
end
有没有办法做到这一点,或者有什么更好的方法来跟踪List 订单而不创建相同Item 的多个实例?
【问题讨论】:
-
你好,你能分享一下模型里面的代码和他们的架构吗?
-
刚刚添加了模型和架构。
标签: ruby-on-rails activerecord associations instance