我正在尝试在rails中使用form_for来同时更新User模型中的两个对象。原因是一个人可以更新自己和其配偶(两个不同的用户)的基本信息,而不必填写两个单独的表格。
我当前用于更新一个用户的代码如下:
<%= form_for(@user, :url=> wizard_path, :method => :put) do |f| %>
<div class="form-group form-question-group">
<%= f.label :state, "What state do you live in?", class: "form-question" %>
<%= f.select(:state, options_for_select(us_states, selected: @user.state), {:prompt => "State"}, :class => "form-control", :required => true) %>
<%= f.hidden_field :user_id, value: @user.id %>
</div>
<div class="form-buttons">
<%= link_to "Back", previous_wizard_path, :class => "align-left" %>
<%= f.submit "Continue", :class => "btn btn-primary align-right" %>
</div>
<% end %>
我如何编辑此表单,以便在提交时不仅会更新当前用户,还会更新该用户的配偶(可以通过@ user.spouse访问)。
我的想法是使用您的用户控制器更新方法
def update
if @user.update_attributes(user_params)
# here you update spouse
spouse = @user.spouse
if spouse.present?
spouse.state = @user.state
spouse.save
end
flash[:success] = 'success'
end
end