嵌套形式的Rails [英] Nested Forms Rails
本文介绍了嵌套形式的Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个型号的用户和地址。
I have 2 models User and Address .
class User < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
class Address < ActiveRecord::Base
belongs_to :user
end
我的控制器
def new
@user = User.new
@user.addresses << Address.new
@user.addresses << Address.new
end
def create
@user = User.new(params[:user])
if @user.save
#do something
else
render 'new'
end
end
和我的视图
<%= form_for @user do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :addresses do |a| %>
<p> Home </p>
<%= a.text_field :state %>
<%= a.text_field :country%>
<%= a.text_field :street %>
<p> Work </p>
<%= a.text_field :state %>
<%= a.text_field :country%>
<%= a.text_field :street %>
<% end %>
<% end %>
<% end %>
我的问题是我得到的只是最后的状态,国家,街道PARAMS输入。
My problem is I get only the last state,country,street entered in params .
"addresses_attributes"=>{"0"=>{"street"=>"test", "state"=>"test",, "country"=>"test"},
"1"=>{"street"=>"", "state"=>"", "country"=>""}}
此外,如果有更好的方式来做到这一点,我将AP preciate任何建议。
Also if there's a better way to do this I will appreciate any suggestions .
推荐答案
的轨API 说, fields_for
将被它反复自我了地址的集合中的每个元素。
The rails API says that fields_for
will be repeated by it self over each element in the collection of addresses.
我会建议增加一种标签到你的地址(如工作,家庭等)。然后它应本身工作。而与此标签的是,当你想添加更多的地址多一点弹性。
I would suggest adding a kind of label to your addresses (like Work, Home, etc). And then it should work by itself. And with this label your are a bit more flexible when you want to add more addresses.
<%= f.fields_for :addresses, @user.addresses do |a| %>
<p> <%= a.object.label %> </p>
<%= a.text_field :state %>
<%= a.text_field :country%>
<%= a.text_field :street %>
<% end %>
这篇关于嵌套形式的Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文