Search code examples
ruby-on-railsrubypostgresqlactiverecordform-helpers

Accessing Model ID inside of rails form helper


First off I'm new to rails, I have a join table Menus_orders which I'm trying to load ID's into on create.

I have this form helper which has access to Order.new(:id, :name) fields and fields_for Menus_order(:menu_id, :order_id). I can insert the menu_id from a select but I can't for the life of me figure out how to populate a hidden input with the current order_id which the form holds in @order.

look at ORDER_ID HERE

<div class="form">
<h1>Create a new order</h1>
  <%= form_for @order do |f| %>
  <%= f.label :name%><br>
  <%= f.text_field :name%><br>
  <h3>Select meals</h3>
  <%= fields_for(@menus_order) do |i| %>
    <div class="field">
      <%= i.select :menu_id, options_for_select(Menu.all.pluck(:id)) %>
      <%= i.hidden_field :order_id, :value =>   ORDER_ID HERE   %>
    </div>
  <% end %>
  <br>
  <%= f.submit "Create"%><br>
  <% end %>
</div>

Thanks, DW


Solution

  • You should use nested attributes for order model just apply the conventions right & it will be handled, you can achieve this by following example :

    order.rb should be like :

    class Order < ActiveRecord::Base
      has_many :menu_orders
      accepts_nested_attributes_for :menu_orders
    end
    

    menu_order.rb be like :

    class MenuOrder < ActiveRecord::Base
    belongs_to :order
    end
    

    orders/new.html

    <div class="form">
    <h1>Create a new order</h1>
      <%= form_for @order do |f| %>
      <%= f.label :name%><br>
      <%= f.text_field :name%><br>
      <h3>Select meals</h3>
      <%= f.fields_for :menu_orders do |i| %>
        <div class="field">
          <%= i.select :menu_id, options_for_select(Menu.all.pluck(:id)) %>
        </div>
      <% end %>
      <br>
      <%= f.submit "Create"%><br>
      <% end %>
    </div>
    

    OrdersController

    class OrdersController < ApplicationController
    
      def new
        @order = Order.new
        @order.menu_orders.build
      end
    
      def create
        @order = Order.new(order_params)
        if @order.save
          redirect_to orders_path
          flash[:success] = "Order created"
        else
          render 'new'
        end
      end
    
      private
    
      def order_params
        params.require(:order).permit(:name, menu_orders_attributes: [ :menu_id, :order_id ])
      end
    end