从特定视图保存其他模型的字段

时间:2009-11-11 13:29:34

标签: ruby-on-rails

我是Ruby On Rails的新手,我正在使用带有登录和用户注册功能的baseApp。它还会在用户注册时为其创建一个空的配置文件。

然后,我创建了一个迁移,以便在配置文件表中添加字段,例如firstName,gender,state,country等。

我想做的是在注册表单中显示这些字段,然后将它们保存在配置文件表中。我怎么能这样做?

谢谢,

布赖恩

1 个答案:

答案 0 :(得分:0)

accepts_nested_attributes_for提供您需要的一切。

只要你让用户拥有一个配置文件就可以了。你好了。

accepts_nested_attributes_for :profile添加到用户模型。然后将表单设置为以下内容:

<% form_for :user do |f| %>
  ...
  User model fields
  ... 
  <% @user.build_profile if @user.profile.nil? %>
  <% f.fields_for :profile do |p| %>
    <%= p.label :first_name %>
    <%= p.text_field :first_name %>
    ...
    Profile model fields
    ...
  <% end %>
<% end %>

控制器无需修改。

阅读FormHelper的嵌套表单部分,了解更多详情。

相关问题