如何将表单数据保存到2个数据表中?

时间:2018-11-10 23:31:52

标签: ruby-on-rails ruby

我希望将表单中的数据保存到2个不同的表中。

我在条带化帐户控制器中创建了这个

     def create

            @stripe_account = StripeAccount.new(stripe_account_params)
            @user = User.find(params[:user_id])
            @stripe_account.user_id = current_user.id



                  acct = Stripe::Account.create({
                  :country => "US",
                  :type => "custom",
                    legal_entity: {
                      first_name: stripe_account_params[:first_name].capitalize,
                      last_name: stripe_account_params[:last_name].capitalize,
                      type: stripe_account_params[:account_type],
                      dob: {
                        day: stripe_account_params[:dob_day],
                        month: stripe_account_params[:dob_month],
                        year: stripe_account_params[:dob_year]
                      },
                      address: {
                        line1: stripe_account_params[:address_line1],
                        city: stripe_account_params[:address_city],
                        state: stripe_account_params[:address_state],
                        postal_code: stripe_account_params[:address_postal]
                      },
                      ssn_last_4: stripe_account_params[:ssn_last_4]
                    },
                    tos_acceptance: {
                      date: Time.now.to_i,
                      ip: request.remote_ip
                    }

            })

            @stripe_account.acct_id = acct.id
    #issue is here at @user
            @user.stripe_token = acct.id

  if @stripe_account.save!
        format.html { redirect_to new_bank_account_path, notice: 'Stripe account was successfully created.' }
        format.json { render :show, status: :created, location: @stripe_account }
      else
        format.html { render :new }
        format.json { render json: @stripe_account.errors, status: :unprocessable_entity }
      end
    end
  end

表单:

  <%= form_for ([@user, @stripe_account]) do | f | %>

用户模型:

  has_one :stripe_account

Stripe_account模型:

  belongs_to :users

acct.id被保存到stripe_account表中,而不是用户表中。用户表中有一条user.stripe_account记录。

如何在两个表中保存acct.id?

1 个答案:

答案 0 :(得分:1)

我猜你只是在做@stripe_account.save而没有做@user.save(为什么要削减方法?)。

您可以添加@user.save或使用autosave: true选项设置当属关联。

我建议您更改此设置:

@stripe_account = StripeAccount.new(stripe_account_params)
@user = User.find(params[:user_id])
@stripe_account.user_id = current_user.id

对此,

@user = User.find(params[:user_id])
@stripe_account = @user.build_stripe_account(stripe_account_params)

如果您仅设置id而不设置实际对象,我认为自动保存将不起作用。