简体   繁体   中英

How to save a rails model with associated model at the same time?

When saving a model in Rails, I want to save another associated model along with it using the first model's ID. IS there a way to do this in Rails 3?

*nevermind

model.build_other. got it. i'm an idiot.

A late answer but you can do it with a before_save callback. Say you have Model1 and Model2. Put the code below into app/models/model1.rb:

before_save :create_model2

def create_model2
  @model2 = Model2.new(params[:id])
  @model2.model1 = self
  @model2.save
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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