2

作成時に cardpacks_controller で呼び出される 15 枚のカードのランダム パックを作成したいと考えています。私は次のモデルを持っています:

カード:

class Card < ActiveRecord::Base
  # relations
  has_many :cardpacks, through: :cardpackcards
  belongs_to :cardset
end

カードパック:

class Cardpack < ActiveRecord::Base
  #relations
  has_many :cards, through: :cardpackcards
  belongs_to :cardset

  # accept attributes
  accepts_nested_attributes_for :cards
end

カードパックカード:

class Cardpackcard < ActiveRecord::Base
  #relations
  belongs_to :card
  belongs_to :cardpack
end

カードセット:

class Cardset < ActiveRecord::Base
  #relations
  has_many :cards
  has_many :cardsets
end

ランダムな card_id 値と同じ cardpack_id を持つ 15 個の Cardpackcards レコードを作成するにはどうすればよいですか (これらは同じパックに属します)

複雑なフォーム シリーズのチュートリアルを見たことがありますが、この問題に取り組む方法がわかりません。

誰かがこの問題を解決するのを手伝ってくれて、Rails 言語についてより多くの洞察を与えてくれることを願っています。

ありがとう、エリック

4

2 に答える 2

0

データベース システムによっては、order random 句を使用して 15 個のランダム レコードを検索できる場合があります。たとえば、Postgres では次のようになります。

Model.order("RANDOM()").limit(15)

ランダム モデルが与えられたらbefore_create、関連付けをセットアップするメソッドを追加できます。

于 2012-09-08T22:19:18.597 に答える
0

Cardpackcardモデルが何もせず、cardsとの間のマッチングを提供する場合は、代わりに関連付けをcardpacks使用できますhas_and_belongs_to_many。これにより、物事が少し単純化されます。

これがないと、コントローラーのコードは次のようになります。

cardset  = Cardset.find(params[:cardset_id])
cardpack = Cardpack.create(:cardset => cardset)

15.times do
  cardpack.cardpackcards.create(:card => Card.create(:cardset => cardset))
end
于 2012-09-08T22:31:05.317 に答える