2011-04-11 115 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