【发布时间】:2017-07-20 23:06:44
【问题描述】:
问这个问题:我正在做的一个学生项目,我修修补补太久了,但无法提出解决方案。
我有一个名为 Game 的类,一个游戏有很多引号。如果我创建一个游戏@game = Game.create,然后将其与角色@game.characters = [@character1, @character2] 关联。由于我的关联,我可以使用@game.quotes(返回数百个对象)访问这两个字符的所有引号。
我希望能够获取 10 个引号的样本,例如 @game.ten_quotes(对象数组)将返回 @game.quotes 的随机样本。我还希望将@game.ten_quotes 保存到数据库中。
我的第一个想法是在迁移中我需要一个新的 Game 属性:
class CreateGames < ActiveRecord::Migration[5.1]
def change
create_table :games do |t|
t.text :state, default: "[]"
t.boolean :completed, default: false
t.something :ten_quotes
# what would this look like if I'm saving an array of objects?
t.timestamps
end
end
end
在下面的 Rails 控制器中,我能够生成十个引号,但我觉得我的工作方向错误:
class Game < ApplicationRecord
has_many :game_logs
has_many :characters, through: :game_logs
has_many :quotes, through: :characters
def generate_quotes
if self.ten_quotes == []
x = quotes.shuffle.sample(10)
self.ten_quotes = x
else
return false
end
end
end
如何获取报价样本,将该样本与游戏实例相关联,然后将游戏实例一次保存到数据库中,以后没有机会覆盖?我需要一个新模型吗?
如果您愿意提供帮助,请提前致谢。否则,祝您有美好的一天!
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord associations