Rails 5通过使用嵌套属性使用父对象创建多个子对象

时间:2017-03-05 03:15:18

标签: ruby-on-rails activerecord orm nested-attributes

所以,我对Rails相当新,因为模型的复杂性而陷入困境。

我有Developer模型,Township模型和Project模型,其内容如下: -

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  

我想创建如下项目: -

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

关于如何实现这一点的任何想法?我还需要了解DeveloperController中所需的强制参数白名单。

1 个答案:

答案 0 :(得分:3)

我不知道你有一种方法可以在一行中创建它(加上它的可读性较差),但你可以使用类似的代码使用rails来实现这一点:

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

保存开发人员将使用正确的外键保存所有其他内容,前提是您已正确设置它们。只需注意你的参数的格式,以确保你正确地循环它。