简体   繁体   中英

Using one form to create two models with overlapping attributes in Rails

This post seems good for how to create two models with one form. But how would you do it if the two models share one or more of the attributes?

That post seems fairly outdated, I would recommend using accepts_nested_attributes_for and fields_for in your form instead. That said, overlapping attributes should probably be set in your model's callbacks. Say you want a project's name to be automatically set to first task's name.

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
  before_validation :set_name_from_task

  private
  def set_name_from_task
    self.name = tasks.first.name
  end
end

If your 2 models are completely unrelated, you can assign certain params to them directly in the controller.

def create
  @foo = Foo.new(params[:foo])
  @bar = Bar.new(params[:bar])

  @bar.common_attr = params[:foo][:common_attr]

  # validation/saving logic
end

Although this is not a great practice, this logic should ideally be moved into models.

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