0

如果已经回答,请原谅我。我花了几个小时在这里和谷歌上寻找这个问题的答案。

我刚刚开始使用 Ruby on Rails。在将最初通过表单提交的数据保存到两个不同的模型后,我正在尝试使用来自 API 响应的数据更新模型。

所以基本上我有一个用户模型和一个角色模型。注册表单收集有关用户及其角色的数据。为了发出 API 请求,我必须至少获得一些关于要作为请求属性(即名称、领域)的一部分传入的角色的详细信息。

所以我使用带有嵌套属性的 form_for :

<%= form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>

      <%= f.label :username %>
      <%= f.text_field :username %>

      <%= f.label :first_name %>
      <%= f.text_field :first_name %>

      <%= f.label :last_name %>
      <%= f.text_field :last_name %>

      <%= f.label :email %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.label :password_confirmation, "Password Confirmation" %>
      <%= f.password_field :password_confirmation %>

      <%= f.fields_for :characters do |builder| %>

        <%= builder.label :realm %>
        <%= builder.text_field :realm %>

        <%= builder.label :name %>
        <%= builder.text_field :name %>

      <% end %>

      <%= f.submit "Sign Up" %>
<% end %>

This successfully submits all of the user info submitted to the User model and the realm and name submitted to the Character model. No problems there. However, I have several more fields that I want t fill in for the Character records just created from the API that provides all of the character info. What is the most efficient way to do this so that after the form submits, it updates the record (or adds data prior to save the record) with the data coming back from the API.

I don't need help on the specific fields and data returned. I have that all working, I'm just looking for a way to make the API request and complete the record with all data immediately after the form submits.

4

1 回答 1

0

Suggest to use callback (:after_create) .

Depending upon the API processing you can choose between them . :after_save :before_save :before_create

With any callback just get the data from your API and fill other character info's.

Hope that helps . Good luck .

于 2012-03-26T09:25:57.583 回答