在父级保存在Rails 4中之后使用创建的嵌套属性对象

时间:2015-08-23 22:57:13

标签: ruby-on-rails

我正在尝试访问在保存父项时使用嵌套属性创建的已创建对象,我不知道该怎么做。我目前的设置如下:

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

2 个答案:

答案 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