Rails 5 create multiple child objects using parent

2019-06-12 11:33发布

问题:

So, I'm fairly new to Rails and I'm stuck due to my model's complexity.

I have a Developer model, a Township model and a Project model and their contents are as follows:-

Developer.rb

Class Developer < ApplicationRecord
  has_many :townships,
  has_many :projects, through: :townships

  accepts_nested_attributes_for :township
end  

Township.rb

Class Township < ApplicationRecord
  belongs_to :developer
  has_many :projects

  accepts_nested_attributes_for :project
end  

Project.rb

Class Project < ApplicationRecord
  belongs_to :township

end  

I want to create projects such as follows:-

project = Developer.create(
          {
           name: 'Lodha',
           township_attributes: [
            {
             name: 'Palava', 
             project_attributes: [
              {
               name: 'Central Park'
              },
              {
               name: 'Golden Tomorrow'
              }
            ]}
          ]})  

Any ideas as to how can I accomplish this? I also need to understand the strong params whitelisting required in the DeveloperController.

回答1:

I don't know of a way for you to create it in one line (plus it would be less readable) , but you can do this with rails using similar code to below:

def create
  developer = Developer.new(name: 'Loha')
  township = developer.townships.build({ name: 'Palava' })
    # for this part I don't know what your form looks like or what the 
    # params look like but the idea here is to loop through the project params like so
  params[:projects].each do |key, value|
    township.projects.build(name: value)
  end

  if developer.save
    redirect_to #or do something else
  end
end

Saving the developer will save all of the other things with the correct foreign keys assuming you have them set up correctly. Just pay attention to the format of your params to make sure you're looping through it correctly.