2012-10-09 58 views
0

在我的Ruby on Rails應用程序中,我創建了一些數據並將其保存在數據庫中,但現在我需要獲取記錄的id(保存時)。我需要得到這個ID,併爲此記錄,在其他表中創建綁定此id的記錄數組(在模型中我有關聯)。在rails中創建數據時獲取記錄的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 

它可以看到作爲一個兩個問題,但主要的是第一部分。

+0

爲什麼你要分配的主鍵?這是一個非常不安全的操作。或者你的意思是你想給你的新價格表'distributor_id'? – varatis

+0

你的問題不清楚。顯示模型並請選擇更好的措辭和說明。 –

+0

分配給一些變量說x和你可以得到id使用x.id –

回答

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 
+0

主要麻煩是這一點,我不知道有多少紀錄將有上pricelist_id,所以:cross_lists_attributes => [ {...}, {...} 不好的choise ... – byCoder

+0

看到編輯例如答案關於如何構建關聯對象。 – rewritten

+0

它會迭代這個創建時,我有多個記錄寫? – byCoder

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 
+0

好吧,稍後再檢查... – byCoder

相關問題