如何将另一个模型的数据写入该模型?

问题描述 投票:0回答:1

我有模型订单和用户。

user - has_many: order

order - belongs_to: user

我想检查订购单。

<% if current_user%>

    form where the name of the order form will be recorded from the user

 <% else%>

    regular order creation form

 <% end%>

任务是如何将另一个模型的数据写入该模型?

ruby-on-rails ruby model-view-controller ruby-on-rails-5 ruby-on-rails-6
1个回答
0
投票

您可以在控制器中执行此操作

例如

Class OrdersController < ApplicationController
  def new
    if current_user
      # this will set the user_id field 
      # you can set additional attributes here
      @order = current_user.orders.build({attribute: value})
    else
      @order = Order.new
    end
  end
  ...

视图中

= form_for @order do |f|
  ...
© www.soinside.com 2019 - 2024. All rights reserved.