0

私のRubyonRailsアプリでは、いくつかのデータを作成してdbに保存していますが、今度はレコードのIDを取得する必要があります(保存時)。このIDを取得する必要があります。このレコードについては、他のテーブルで、このIDにバインドされたレコードの配列を作成します(モデルでは、関連付けがあります)。

  PriceList.create(:distributor_id => distributor_id, :brand => brand, :article_nr => num_catalog, :price => price, :quantity => quantity, :waittime => waittime)

class PriceList < ActiveRecord::Base
  has_many :cross_lists
  belongs_to :distributor
end




class CrossList < ActiveRecord::Base
  belongs_to :price_list
end

1つに2つの質問として表示される可能性がありますが、メジャーは最初の部分です。

4

2 に答える 2

0

そのIDにバインドされたレコードの配列が価格表のコレクションではないのはなぜですか?このように、それはすべて自動的に行われ、あなたはそれについて心配する必要はありません。

class PriceList < ActiveRecord::Base

  ....
  has_many :records
end

class Record < ActiveRecord::Base

  belongs_to :price_list
end

今、あなたは次のようなことをすることができます:

PriceList.create(:distributor_id => distributor_id, ....., :records => [Record.new, Record.new])

IDの割り当てやトランザクションの追加について心配する必要がないため、はるかに簡単です。ActiveRecordがそれを処理します。

しかし、最初の質問に答えるには、レコードがデータベースに保存されるまでIDはありません。したがって、コードでIDを取得するには:

rec = PriceList.create(:distributor_id => distributor_id, :brand => brand, :article_nr => num_catalog, :price => price, :quantity => quantity, :waittime => waittime)
rec.id #=> returns the id from db
于 2012-10-09T19:21:13.580 に答える
0

最も簡単な方法は設定することです

class PriceList < ActiveRecord::Base
  has_many :cross_lists
  accept_nested_attributes_for :cross_lists # <- this line
  belongs_to :distributor
end

次に、配列内のcross_listsのデータを渡します。

PriceList.create(:distributor_id => distributor_id, 
                 :cross_lists_attributes => [
                   {...},
                   {...}
                 ]
                )

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

関連するモデルやそのプロパティが手元にない場合は、メインレコードを保存/作成した後、その場でモデルを作成できます。

@price_list = PriceList.create(...)
if @price_list.persisted?
  # now the @price_list object has an ID

  @price_list.cross_lists.create(...)
  # one CrossList record has been created, and its price_list_id
  # field has been automatically populated
end
于 2012-10-09T20:31:04.800 に答える