gpt4 book ai didi

ruby-on-rails - 嵌套 form_for

转载 作者:行者123 更新时间:2023-12-04 03:34:34 26 4
gpt4 key购买 nike

我的项目是这样组织的:用户是主要资源,每个用户都有一个配置文件,每个配置文件都有一个位置,如下所示:

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

现在我必须构建一个表单来插入所有个人资料信息,但也要插入位置信息(地址等)。如果我编写以下代码,它不会关心位置。

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

有人对这种情况有什么建议吗?

谢谢

最佳答案

如果您想在同一个表单中访问不同的模型,您可以使用 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 %>

关于ruby-on-rails - 嵌套 form_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5617981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com