簡體   English   中英

如何以Rails方式獲取新創建的記錄的ID?

[英]How to get the id of the newly created record in rails way?

我有2個模型,假設是model1model2 model1有很多model2 model2 屬於 model1 同時保存model1model2

class Model1 < ActiveRecord::Base
  has_many :model2s
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
end

def create
   @mod1 = Model1.new(model1_params)
   id = Model1.last.id + 1
   @mod2 = Model2.new(model1_id: id)
   if @mod1.save && @mod2.save 
    redirect root_path
   else
    render 'edit'
   end
end

在我刪除model1的最后一條記錄之前,該解決方案是可以的。 我如何獲得model1創建之前的最后一條記錄。

實現此目的的最合理的方法是這樣的:

def create
  @mod1 = Model1.new(model1_params)
  @mod1.model2.build({args if you have them}) # this will only work if you have the relationship set up
  if @mod1.save
    # @mod1 is now saved along with model 2 who now has its ID
    # @mod1.id returns id, Model2.last returns model2 ID, Model2.last.model1_id returns Model1 ID
    #you can now delete model 1 if you wanted to, just make sure you don't have dependent destroy on in the model1.
    redirect root_path
  else
    render 'edit'
  end
end

希望能幫助到你!

如果Model1和Model2的子類ActiveRecord::Base ,則無需手動設置id,實際上,這是一種反模式。

Rails使用ActiveRecord::Base為模式支持的類建模。 假設您有一個名為model1s的數據庫表。 當您像這樣創建Model1類時

class Model1 < ActiveRecord::Base
end

Rails知道相應的數據庫表是models1 (從名稱推斷出來),並且在保存新的Model1記錄后會自動生成一個ID。 id通常是一個自動遞增的整數。 當然,這取決於基礎數據庫引擎(MySQL,Postgresql,SQLite等)

因此,在您的示例中,您可以

success = false
@mod1 = Model1.new(model1_params)
if @mod1.save
  @mod2 = Model2.new(model1_id: model1.id)
  success = true if @mod2.save
end
success ? redirect_to(root_path) : render('edit')

一些更多的技巧。 Model2的model1_id屬性看起來像是一個外鍵。 您應該研究利用has_many / has_one / belongs_to關聯來以更慣用的Rails方式完成所需的操作

class Model1 < ActiveRecord::Base
  has_one :model2
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
end

# Then you can do (one of the many options)
@mod1 = Model1.create(params)
@mod1.model2.create

檢查ActiveRecord上的Rails指南很有用。

我假設您使用的是ActiveRecord,因為您使用的是.last.save方法。 我希望我的直覺是正確的。

無法獲得尚未創建的記錄的ID。 解決方案的最佳答案是先保存@ mod1。 並獲取其ID的ID。

def create
  @mod1 = Model1.new(model1_params)

  if @mod1.save && Model2.create(model1_id: @mod1.id) 
    # @mod1 is now saved to the database. So @mod1.id will return id.
    redirect root_path
  else
    render 'edit'
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM