Search code examples
ruby-on-railsrubymodel-view-controllerruby-on-rails-5ruby-on-rails-6

how to write data of another model to the model?


I have a model order and user.

user - has_many: order

order - belongs_to: user

I want to make a check on the order form.

<% if current_user%>

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

 <% else%>

    regular order creation form

 <% end%>

the task is how to write data of another model to the model?


Solution

  • You can do this in the controller

    for eg.

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

    in view

    = form_for @order do |f|
      ...