我正在尝试通过表单提交向用户模型添加地址,但我遇到了麻烦。用户:
class User < ActiveRecord::Base
has_many :addresses
end
可以通过帐户控制台控制的帐户页面为其帐户添加地址。
class AccountsController < ApplicationController
def addresses
@user = current_user
@addresses = @user.addresses
default_country = Country.find Spree::Config[:default_country_id]
@countries = Checkout.countries.sort
@states = default_country.states.sort
end
end
在“/ accounts / addresses”视图中,我有一个我要提交的表单:
<% form_for @user do |user_form| %>
<% user_form.fields_for :address do |address_form| %>
<%= address_form.text_field :firstname, :class => 'required', :value=>"" -%>
<%= address_form.text_field :lastname, :class => 'required', :value=>"" -%>
<%= address_form.text_field :business_name, :class => 'required', :value=>"" -%>
<%= address_form.text_field :address1, :class => 'required', :value=>"" -%>
<%= address_form.text_field :address2, :value=>"" %>
<%= address_form.text_field :city, :class => 'required', :value=>"" -%>
...
<%= address_form.submit %>
<% end -%>
<% end %>
我在这里查看一对多fields_for代码:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
但问题是我有多个地址但只想一次提交一个地址。我需要添加到用户/地址模型和/或帐户控制器中,以便在提交该表单时成功创建地址并将其添加到用户模型中?如果有更简单的方法来实现这一目标,请告诉我。
答案 0 :(得分:0)
您需要accepts_nested_attributes_for
class User < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
你的表格可能是
<% form_for @user do |user_form| %>
<% user_form.fields_for :addresses do |address_form| %>
<%= address_form.text_field :firstname, :class => 'required' -%>
<%= address_form.text_field :lastname, :class => 'required' -%>
<%= address_form.text_field :business_name, :class => 'required' -%>
<%= address_form.text_field :address1, :class => 'required' -%>
<%= address_form.text_field :address2 %>
<%= address_form.text_field :city, :class => 'required' -%>
...
<%= address_form.submit %>
<% end -%>
<% end %>
这可以让你编辑所有现有地址,如果你需要在列表中加1,你可以
在控制器操作中 @user.addresses.build
填充一个空的。