【问题标题】:how to write data of another model to the model?如何将另一个模型的数据写入模型?
【发布时间】:2020-05-07 19:08:38
【问题描述】:

我有一个模型订单和用户。

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】:

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

    例如。

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

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-13
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多