创建嵌套模型表单

发布于 2024-10-10 04:48:33 字数 349 浏览 0 评论 0原文

我正在尝试构建一个多模型表单 - 但问题之一是我需要链接表单内的模型。

例如,假设我的表单具有以下模型:用户、配置文件

创建新用户时,我想同时创建一个新配置文件,然后链接两者。问题是,如果两者都还没有创建,那么它们还没有 ID - 那么我如何分配链接值?

谢谢!

-Elliot

我注意到,有些人喜欢这个 - 要查看有关链接两个模型的更多信息,请查看我的第二个问题,其中有答案:以多模型形式链接两个模型

I'm trying to build a multi model form - but one of the issues, is I need to link the models within the form.

For example, lets say the form I have has the following models: Users, Profiles

When creating a new user, I'd like to create a new profile simultaneously, and then link the two. The issue is, if neither have been created yet, they don't have ID's yet - so how can I assign linking values?

Thanks!

-Elliot

I noticed, some people are favoriting this - to view more about linking the two models, check out my second question which has the answer: Linking two models in a multi-model form

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坦然微笑 2024-10-17 04:48:33

实现所需结果的一种方法是,您可以制作一个利用 Rails 中的嵌套属性支持的表单:

<%= form_for(@user) do |f| %>
  <%= f.label :my_user_attribute %>
  <%= f.text_field :my_user_attribute %>

  <%= f.fields_for :profile do |fp| %>
    <p>
      <%= fp.label :my_profile_attribute %>
      <%= fp.text_field :my_profile_attribute %>
    </p>
  <% end %>    

  <%= f.submit %>
<% end %>

您还需要将以下内容添加到您的 User 类中:

accepts_nested_attributes_for :profile

您可以阅读有关 Active Record 嵌套属性的更多信息 此处
您可以在此处阅读有关 ActionView 表单助手的更多信息(在页面中搜索)对于“嵌套属性示例”)。

如果您使用此方法,并对两个模型进行良好的验证,则不必担心跟踪数据库 ID,因为 ActiveRecord 将同时创建两者(但直到两个模型对象都有效)。

One way to achieve the desired result is that you can craft a form that takes advantage of nested attributes support in Rails:

<%= form_for(@user) do |f| %>
  <%= f.label :my_user_attribute %>
  <%= f.text_field :my_user_attribute %>

  <%= f.fields_for :profile do |fp| %>
    <p>
      <%= fp.label :my_profile_attribute %>
      <%= fp.text_field :my_profile_attribute %>
    </p>
  <% end %>    

  <%= f.submit %>
<% end %>

You will also need to add the following to your User class:

accepts_nested_attributes_for :profile

You can read more about Active Record Nested Attributes here.
You can read more about the ActionView Form Helpers here (search down the page for "Nested Attributes Examples").

If you use this approach, along with good validations on both models, you won't have to worry about tracking the database IDs, because both will be created at the same time by ActiveRecord (but not until both model objects are valid).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文