简体   繁体   English

自动创建“ belongs_to”记录

[英]Auto-create `belongs_to` record

Similar questions have been asked before but I just can't figure this out. 之前也曾提出过类似的问题,但我无法弄清楚。

So I have Model_A and Model_B. 所以我有Model_A和Model_B。 Model_B belongs_to Model_A. Model_B belongs_to Model_A。 What I want to do is when I create Model_A is to automatically call the create method for Model B. Then a script takes over a generates a bunch of data for Model_B. 我要做的是在创建Model_A时自动调用Model B的create方法。然后脚本接管了一个,为Model_B生成一堆数据。 I use after_create because this only has to happen once. 我使用after_create因为这只需要发生一次。

It needs done this way. 它需要以此方式完成。 If you wanna know the details feel free to ask... 如果您想知道细节,请随时询问...

So I got Model_A here. 所以我在这里得到了Model_A。 I just can't seem to get the right syntax in create_model_b . 我只是似乎无法在create_model_b获得正确的语法。 In the example I used I just get an error saying the method doesn't exist for Model_A. 在我使用的示例中,我只是得到一个错误,指出该方法对于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 doesn't do anything special really: 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

Thanks! 谢谢!

Two ways: 两种方式:

1. 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. 2。

class Model_A < ActiveRecord::Base
  after_create :create_model_b

   ...

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

Your Model A contains half of an association: belongs_to :Model_B 您的模型A包含一半的关联: belongs_to :Model_B

Your Model B is missing its association to Model A. 您的模型B缺少与模型A的关联。

Depending on the relationship you set up, you can complete the association with a has_one :Model_A , or has_many :Model_A , for example. 例如,根据您设置的关系,您可以使用has_one :Model_Ahas_many :Model_A完成关联。

Here's Active Record documentation for reference. 这是Active Record文档供参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM