我有一个模型徽章:
t.string :title
t.string :description
t.string :image
t.integer :points
一个模型用户:
t.string :first_name
t.string :last_name
t.integer :total_points
t.integer :used_points
我需要的是向用户添加徽章,以便用户可以查看/查看他们拥有的徽章以及他们是否已经收集了积分。谢谢!
假设您希望许多用户拥有相同的徽章,您需要的是徽章和用户之间的多对多关联。用户可以拥有许多徽章,徽章可以拥有许多用户。这需要一个连接表来存储哪个用户有哪些徽章。
create_table :badges_users do |t|
t.belongs_to :user, index: true
t.belongs_to :badge, index: true
end
由于它只是一个列表,因此不需要此表的模型。使用has_and_belongs_to_many
。
class Badge < ApplicationRecord
has_and_belongs_to_many :users
end
class User < ApplicationRecord
has_and_belongs_to_many :badges
end
向用户添加徽章就像推送到阵列一样简单。
user.badges << badge
或相反亦然。
badge.users << user
他们做同样的事情,用徽章和用户ID为badges_users
添加一行。
See here for more about how to use these collections。
而不是将用户的点存储在用户中,而是从他们的徽章计算它们。
def total_points
badges.sum(:points)
end
如果您需要跟踪用户是否“收集”了徽章,您需要将其存储在连接表中并使用模型来获取该信息。
create_table :badge_users do |t|
t.belongs_to :user, index: true
t.belongs_to :badges, index: true
t.boolean :collected, default: false
end
class BadgeUser < ApplicationRecord
belongs_to :user
belongs_to :badges
end
然后使用has_many
and has_many :through
建立关联。
class User < ApplicationRecord
has_many :badge_users
has_many :badges, through: :badge_users
end
class Badge < ApplicationRecord
has_many :badge_users
has_many :users, through: :badge_users
end
向用户添加徽章与以前一样,user.badges << badge
。
然后我们让用户收集徽章。
# In BadgeUser
def collect
if collected
raise "Badge already collected"
end
update!(collected: true)
end
# In User
def collect_badge(badge)
badge_users.find_by( badge: badge ).collect
end
用户可以找到他们收集的徽章。
# In User
def collected_badges
badges.merge(BadgeUser.where(collected: true))
end
一旦用户找到他们收集的徽章,他们就可以总计他们的积分,以找出他们使用了多少积分。
# In User
def used_points
collected_badges.sum(:points)
end