按复选框创建关联资源

时间:2012-08-08 10:01:19

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

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

模型/ 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

模型/ engineer.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

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

1 个答案:

答案 0 :(得分:1)

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

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

在观察者中将new更改为create!

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