Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Controller Method in link_to from the view

My application has deals which have orders. In my admin area I want to be able to process the orders manually.

In my access/deals view

<%= link_to "Process Orders", "Not sure what I put here?" %>

in my access/deals_controller

def process_orders
   @deals = Deal.find(params[:id]
   @orders = @deals.orders.where("state" == ?, "pending")

   @orders.each do |order|
     #order processing code here
   end
end

How should I structure my link_to method to call the process_orders method in my admin/deals controller?

I thought something like

<%= link_to "Process Orders", access_deal_path(deal) %>

which give me the following url

 localhost:3000/access/deals/9

how do I get something like

localhost:3000/access/deals/9/process_orders

I'm also open to suggestions on moving the processing_orders method to model or helper if that is a better way of doing this.

My excerpt of my routes file.

  resources :deals do
    resources :orders
  end

  namespace "access" do
    resources :deals, :podcasts, :pages, :messages
  end
like image 339
Robert B Avatar asked Jul 27 '11 15:07

Robert B


People also ask

Can we call controller method in model rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended.

How does link_ to work in Rails?

Rails is able to map any object that you pass into link_to by its model. It actually has nothing to do with the view that you use it in. It knows that an instance of the Profile class should map to the /profiles/:id path when generating a URL.

What is call method in Rails?

It is used to call back a piece of code that has been passed around as an object.


1 Answers

You can do 1 of the following:

Create a custom route:

match 'access/deals/:id/process_orders' => 'access/deals#process_orders', :as => 'access_deal'

then you can use this link_to:

<%= link_to "Process Orders", access_deal_path(deal) %>

OR

Add a member route:

namespace "access" do
    resources :deals do
        member do
            get :process_orders
        end
    end
end

Your link_to will look something like this:

<%= link_to "Process Orders", process_orders_access_deal_path(deal) %>
like image 170
Kevin Tsoi Avatar answered Oct 06 '22 01:10

Kevin Tsoi