簡體   English   中英

自動創建“ belongs_to”記錄

[英]Auto-create `belongs_to` record

之前也曾提出過類似的問題,但我無法弄清楚。

所以我有Model_A和Model_B。 Model_B belongs_to Model_A。 我要做的是在創建Model_A時自動調用Model B的create方法。然后腳本接管了一個,為Model_B生成一堆數據。 我使用after_create因為這只需要發生一次。

它需要以此方式完成。 如果您想知道細節,請隨時詢問...

所以我在這里得到了Model_A。 我只是似乎無法在create_model_b獲得正確的語法。 在我使用的示例中,我只是得到一個錯誤,指出該方法對於Model_A不存在。

class Model_A < ActiveRecord::Base
  belongs_to :Model_B
  after_create :create_model_b

...

  def create_model_b
     #so I tried a bunch of stuff here but none of it worked
     #I need to create a Model_B which will contain the current Model_A id
     #ex. self.model_b.create(model_a_id: self.id)
  end
end

Model_B實際上並沒有做任何特別的事情:

class Model_B < ApplicationController
def create
    @model_b = Model_B.new(model_b_params)
    create_the_data

    respond_to do |format|
      if @model_b.save
           #redirect
      else
        #uh oh
      end
    end
  end
end

謝謝!

兩種方式:

1。

class Model_A < ApplicationController

def create
  @model_a = ModelA.new(model_a_params)
  if @model_a.save
    ModelB.create(model_a_id: @model_a.id, .....)
    #create data for model B either here or with after_create (of model B)
    redirect_to somewhere_awesome_path
  else
     # rescue error
     render 'new'
  end
end

2。

class Model_A < ActiveRecord::Base
  after_create :create_model_b

   ...

  def create_model_b
    ModelB.create(model_a_id: id)
  end
end

您的模型A包含一半的關聯: belongs_to :Model_B

您的模型B缺少與模型A的關聯。

例如,根據您設置的關系,您可以使用has_one :Model_Ahas_many :Model_A完成關聯。

這是Active Record文檔供參考。

暫無
暫無

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

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