如何在Rails表单中一次保存两个对象?

时间:2016-05-25 14:06:55

标签: ruby-on-rails ruby-on-rails-4 model foreign-keys relation

我正在使用Rails 4.2.3。如何使用一个表单保存两个对象?我有这两个模型......

class MyObject < ActiveRecord::Base
  belongs_to :user
  has_many :my_object_times
  attr_accessor :hour, :minute, :second

  accepts_nested_attributes_for :my_object_times
end

class MyObjectTime < ActiveRecord::Base
  belongs_to :my_object
end

我想提交一个创建MyObject和MyObjectTime对象的表单。所以我创建了我的表单

<%= form_for @my_object do |f| %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label "Time" %>
    <%= select_tag('my_object[hour]', options_for_select((0..12).to_a), {:prompt => 'Select Hour'} ) %> hrs
    <%= select_tag('my_object[minute]', options_for_select((0..60).to_a), {:prompt => 'Select Minutes'} ) %> min
    <%= select_tag('my_object[second]', options_for_select((0..60).to_a), {:prompt => 'Select Seconds’} ) %> sec
    <%= f.fields_for :my_object_time do |mot| %>
      <%= mot.number_field :time_in_ms %>
    <% end %>
  </div>

  <div class="actions">
    <%= button_to "Save", { :action => "create" }, :method => :post, :class => 'button' %>
  </div>
<% end %>

这是我的控制器......

  def create
    @my_object = MyObject.new(my_object_params)
    @current_user = User.find(session["user_id"])
    @my_object.user = @current_user
    if @my_object.save
      respond_to do |format|
        format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
      end
    else
      format.html { render action: "index" }
    end
  end

  private

    def my_object_params
      # Main Code goes here
      params[:my_object][:time_in_ms] = (params[:my_object][:hour].to_i * 60 * 60 + params[:my_object][:minute].to_i * 60 + params[:my_object][:second].to_i) * 1000
      params.require(:my_object).permit(:name, my_object_times_attributes: [:time_in_ms])
    end

但是,只保存MyObject对象而不是相应的MyObjectTime。有没有办法可以让两者同时创建?我不希望出现一个被创建而第二个没出现的情况。我希望两者都被创建或根本没有发生任何事情并返回错误。

1 个答案:

答案 0 :(得分:0)

由于您有has_many :my_object_times,因此应使用my_object_times 复数 )代替my_object_time fields_for和my_object_params方法中的

<%= f.fields_for :my_object_times do |mot| %>

并确保 new方法

中的em>
#my_object_controller
def new
  @my_object = MyObject.new
  @my_object.my_object_times.build
end