0

我正在尝试通过陆军表单中的复选框创建工程师,但它没有被创建。复选框的名称是siege并且是我的Army模型的一部分:

模型/军队.rb

class Army < ActiveRecord::Base
 attr_accessible :siege
 attr_reader :siege
 validates_inclusion_of :siege, :in => [true, false]
 has_many :engineers

 def siege=(string_value)
   @siege = (string_value == '1')
 end
end

模型/工程师.rb

class Engineer < ActiveRecord::Base
  belongs_to :user
  belongs_to :army
end

军队/new.html.erb

<%= form_for @army do |f| %>
  <%= f.check_box :siege %>
  <%= f.submit "Create Army" %>
<% end %>

控制器/armies_controller.rb

def new
  @army = Army.new
end

def create
  @army = current_user.armies.build(params[:army])
    if @army.save
      redirect_to new_army_path
    else
      render :new
    end
  end
end

模型/army_observer.rb

class ArmyObserver < ActiveRecord::Observer
  def after_save(army)
    if army.siege
      Engineer.new({ :user_id => current_user.id, :army_id => :army_id })
    end
  end
end

军队被创建,但工程师没有。我的代码中需要更正哪些内容才能启用此功能?

4

1 回答 1

1

初始化后您没有保存记录:)

.new只是建立一个记录不保存它。

在观察者更改newcreate!

Engineer.new({ :user_id => current_user.id, :army_id => :army_id })

Engineer.create({ :user_id => current_user.id, :army_id => :army_id })

或者在建立记录后保存

engineer= Engineer.new({ :user_id => current_user.id, :army_id => :army_id }) 
engneer.save

您还需要让您的观察者在配置中注册以使其监听活动

http://guides.rubyonrails.org/active_record_validations_callbacks.html#registering-observers

于 2012-08-08T10:23:10.563 回答