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

how to write data of another model to the model?

我有模型订单和用户。

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%>

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

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

例如

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|
  ...

你可以试试accepts_nested_attributes_for