2011-04-11 114 views
2

我以这种方式组织项目:用户是主要的资源,每个用户都有一个配置文件,每个配置文件都有一个位置如下:嵌套的form_for

resources :users do  
    resource :profile, :controller => "profiles" do 
     resource :location 
end 

现在我要建立插入表单所有的资料信息,但位置信息(地址等)。 如果我写下面的代码,它不关心的位置。

<%= form_for(@profile, :url=>{:action=>'update'}, :html => {:multipart => true}) do |f| %> 

有人对此有所建议吗?

TNX

回答

5

如果你愿意,你可以使用accepts_nested_attributes_for相同的形式中访问不同的模型。这里是关于这个话题的一个很棒的截屏:http://railscasts.com/episodes/196-nested-model-form-part-1

你的代码应该是这样的。

#profile.rb 

accepts_nested_attributes_for :location 

在你看来:

<%= form_for(@profile, :url=>{:action=>'update'}, :html => {:multipart => true}) do |f| %> 
    <%= f.fields_for :location do |l| %> 
    //location fields here, for example: 
    <%=l.text_field :city %> 
    <% end %> 
<% end %> 
+0

如果一个配置文件可以有多个位置,该如何实现? – Wit 2017-06-22 08:39:20

4

使用:

form_for [@user, @profile, @location], :action => :update, :html => {:multipart => true} 
+0

的form_for [@user,@profile,@location]:动作=>:更新:HTML => {:多=>真正做} | F | f.textfield:location ??????????? – Joe 2011-04-11 07:34:43

+0

是否可以访问配置文件的first_name和位于同一个form_for中的位置的地址?如果是,如何?请给我一个例子。 Tnx – Joe 2011-04-11 07:45:13