首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails5.1使用nested_attributes_for更新连接表上的属性

Rails5.1使用nested_attributes_for更新连接表上的属性
EN

Stack Overflow用户
提问于 2018-03-06 02:43:02
回答 1查看 147关注 0票数 0

我的API-only后台有三个模型-- UserGameOwnership,它们充当了用户和游戏之间的连接表。

我有一个服务方法,它调用远程API来获取用户拥有的游戏的数据。然后,它使用这些数据将相关游戏添加到数据库中,并使用额外数据(game_count)更新用户,并创建用户与其游戏之间的关系。我可以像这样完成这个任务:

代码语言:javascript
运行
复制
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,并调用

代码语言:javascript
运行
复制
g.ownerships_attributes = [{
  playtime: data[:playtime_forever]
}]

在更新用户之前,但这似乎没有任何影响。我觉得这肯定有一个优雅的解决方案,我只是没有看到它。

以下是我的模型的代码:

User.rb

代码语言:javascript
运行
复制
class User < ApplicationRecord
  has_many :ownerships
  has_many :games, through: :ownerships
end

Game.rb

代码语言:javascript
运行
复制
class Game < ApplicationRecord
  has_many :ownerships
  has_many :owners, through: :ownerships, source: :user
end

Ownership.rb

代码语言:javascript
运行
复制
class Ownership < ApplicationRecord
  belongs_to :user
  belongs_to :game
end
EN

回答 1

Stack Overflow用户

发布于 2018-03-07 10:40:59

在迭代游戏时,将播放时间保存在散列中(以game.id为键)

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
user.ownerships.find_each do |own|
  own.update_attributes(:playtime => playtimes[:own.game_id])
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49117381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档