jasonng
jasonng

Reputation: 107

Retrieving Order details using id

The shopping cart app I'm building using Rails 4.1 has an order_type model with the schema:

create_table "order_types", force: true do |t|
    t.string   "order_name"
    t.integer  "max_limit"

This belongs to the Orders model. Users can pick the order type from the new order page and I use collection select to display this. The order_type_id is saved to each order that's created. The order controller.rb:

class OrdersController < ApplicationController
    def new
        @order = Order.new
        @item = @order.items.build
    end

    def index
        @orders = Order.all
    end

    def show
        @order = Order.find(params[:id])
            @items = Item.where(:order_id => @order.id)
    end

    def create
        @order = current_user.orders.new(order_params)
        respond_to do |format|
            if @order.save
                OrderMailer.order_submission(@order).deliver
                format.html { redirect_to @order, notice: 'Order Submitted.' }
                format.json { render :show, status: :created, location: @order }
            else
                format.html { render :new }
                format.json { render json: @order.errors, status: :unprocessable_entity }
            end
        end
    end

Here's the collecton select used in the form:

<div class="form-group">
                <%= f.label :order_type_id %><br>
                <%= f.collection_select(:order_type_id, OrderType.all, :id, :order_name, prompt: true, class: "form-control")  %>
            </div>

I would like to retrieve and display the Order Type details based on the order_type_id that's stored. How do I do this?

Upvotes: 1

Views: 115

Answers (2)

user3252359
user3252359

Reputation:

You can write a function in ApplicationHelper for example : get_order_type_details_by_id(order_type_id) and simply return the order details. You can directly call that helper function from any view templates. As functions defined in ApplicationHelper is accessible in all views.

Or you can use association for getting the order details

Upvotes: 1

phillyslick
phillyslick

Reputation: 571

<%= @order.order_type %> 

Will get you the OrderType associated with that particular order. Then it is just:

<%= @order.order_type.order_name %>

To retrieve an attribute on the OrderType.

Upvotes: 1

Related Questions