Rails 5 通过使用嵌套属性使用父对象创建多个子对象
Rails 5 create multiple child objects using parent object by the use of 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
.
中所需的强参数白名单
我不知道有什么方法可以让你在一行中创建它(而且它的可读性会更差),但是你可以通过 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
保存开发人员将使用正确的外键保存所有其他内容,前提是您已正确设置它们。请注意参数的格式,以确保正确循环。
所以,我是 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
.
我不知道有什么方法可以让你在一行中创建它(而且它的可读性会更差),但是你可以通过 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
保存开发人员将使用正确的外键保存所有其他内容,前提是您已正确设置它们。请注意参数的格式,以确保正确循环。