开发者

Rails: create parent, using parents own view, while creating child record

开发者 https://www.devze.com 2023-01-22 21:35 出处:网络
While part way through entering a new record(child), that is incomplete and can\'t be saved, I want to be able to add a record to another model(parent) and then use it to complete the original record(

While part way through entering a new record(child), that is incomplete and can't be saved, I want to be able to add a record to another model(parent) and then use it to complete the original record(child). The parent has many required attributes, not just a single field. I want to do it in as dry a way as possible using the new/create view and validations of each model.

The examples I've seen all show how to enter the parent and child data on the one form using accepts_nested_attributes_for. I want to do it in reverse creating a new child and then use the parents own forms to add them if they don't already exist.

eg this sales enquiry model which has a number of parent models

class Enquiry < ActiveRecord::Base
  belongs_to :salesperson
  belongs_to :customer
  belongs_to :site
end

I want to create a new enquiry and select the customer and site which may or may not already be in the database. If they are in the db an autocomplete will find them, otherwise I need to add a new customer or site. The customer requires more than just a single attribute like a name to be entered. It also requires other details like address, contact, etc. I don't want to build the customer form into the enquiry form as I will have the need to add new customers from many other parts of the application. Therefore I only ever want to use and maintain the one customer form: customer->new.html.erb. The enquiry can't be saved without a customer so I need a way to keep the partially entered data.

Two ways开发者_开发问答 I can think to do it.

  1. Store what ever enquiry data has been partially entered in the session, open the new customer view and once its complete redirect back to the enquiry form and display the data thats been entered so far.

  2. Some sort of lightbox popup that can use the new view of the parent model and still keep the enquiry form open in the background.

Will either of them work? If so can someone show me some sample code of how to make it work? Otherwise, is there another better way to do it?


You can use the same system of nested_attributes style.

In your form you can define an attributes with enquiry[customer_attributes][name]. After you just need define in your enquiry model this attribute

class Enquiry < AR

  def customer_attributes=(params)
    self.customer = Customer.create(params)
  end
end

So if there are the params the customer is create. If there are a enquiry[customer_id] is not and you generate the association.

0

精彩评论

暂无评论...
验证码 换一张
取 消