我正在尝试访问在保存父项时使用嵌套属性创建的已创建对象,我不知道该怎么做。我目前的设置如下:
FOO-model.rb
class Foo < ActiveRecord::Base
has_many :bars, dependent: :destroy
accepts_nested_attributes_for :bars
end
棒model.rb
class Bar < ActiveRecord::Base
belongs_to :foo
end
FOOS-controller.rb
class FoosController < ApplicationController
def create
@foo = Foo.create(foo_params)
if @foo.save
# What I want to do is essentially this
bar.do_something
# Redirect
redirect_to path
end
end
private
def foo_params
params.require(:foo).permit(:attribute, bar_attributes: [:id, :attribute1])
end
end
答案 0 :(得分:0)
Foo.create将触发'save'事件。相反,这样做
class FoosController < ApplicationController
def create
@foo = Foo.new(foo_params)
if @foo.save
redirect_to path
end
end
end
在模型中,添加
class Foo < ActiveRecord::Base
has_many :bars, dependent: :destroy
accepts_nested_attributes_for :bars
after_save :bars_do_something
def bars_do_something
bars.each{|b| b.do_something}
end
end
不是更新每个中的foo.bars(根据law of Demeter而不是一个好主意),你可以在创建后更新吧
class Bar < ActiveRecord::Base
belongs_to :foo
after_create :do_something
def do_something
do_something
end
end
答案 1 :(得分:0)
首先,在::new
上使用::create
,而不是Foo
。
def create
@foo = Foo.new(foo_params)
if @foo.save
在#save
来电之后,您可以自由对关联的Bars
执行任何操作:
if @foo.save
@foo.bars.each do |bar|
bar.do_something
end