我正在使用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。有没有办法可以让两者同时创建?我不希望出现一个被创建而第二个没出现的情况。我希望两者都被创建或根本没有发生任何事情并返回错误。
答案 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
方法
#my_object_controller
def new
@my_object = MyObject.new
@my_object.my_object_times.build
end