我的API-only后台有三个模型-- User、Game和Ownership,它们充当了用户和游戏之间的连接表。
我有一个服务方法,它调用远程API来获取用户拥有的游戏的数据。然后,它使用这些数据将相关游戏添加到数据库中,并使用额外数据(game_count)更新用户,并创建用户与其游戏之间的关系。我可以像这样完成这个任务:
class GameService
def self.getGamesForUser(user)
# response hash gets populated here
games = response[:games].map do |data|
Game.find_or_create_by(app_id: data[:appid]) do |g|
g.name = data[:name]
g.icon = data[:img_icon_url]
g.logo = data[:img_logo_url]
end
end
user.update games: games, game_count: response[:game_count]
end
end到现在为止还好。在更新用户时,自动创建用户和游戏之间的所有权关联。但我也想在同一时间(如playtime)向连接表添加额外的属性。我还没能找到一个很好的解决方案。我尝试通过将accepts_nested_attributes_for :ownerships添加到游戏模型来查看nested_attributes_for,并调用
g.ownerships_attributes = [{
playtime: data[:playtime_forever]
}]在更新用户之前,但这似乎没有任何影响。我觉得这肯定有一个优雅的解决方案,我只是没有看到它。
以下是我的模型的代码:
User.rb
class User < ApplicationRecord
has_many :ownerships
has_many :games, through: :ownerships
endGame.rb
class Game < ApplicationRecord
has_many :ownerships
has_many :owners, through: :ownerships, source: :user
endOwnership.rb
class Ownership < ApplicationRecord
belongs_to :user
belongs_to :game
end发布于 2018-03-07 10:40:59
在迭代游戏时,将播放时间保存在散列中(以game.id为键)
games = response[:games].map do |data|
playtimes = Hash.new
game = Game.find_or_create_by(app_id: data[:appid]) do |g|
g.name = data[:name]
g.icon = data[:img_icon_url]
g.logo = data[:img_logo_url]
end
#This is outside the find_or_create_by because it must be done for all games, not just the newly created.
playtimes[game.id] = data[:playtime_forever]
end最后,更新游戏后,更新join表中的playtime:
user.ownerships.find_each do |own|
own.update_attributes(:playtime => playtimes[:own.game_id])
endhttps://stackoverflow.com/questions/49117381
复制相似问题