Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I create a custom route in rails where I pass the id of an existing Model?

I created the following route:

  map.todo "todo/today",
            :controller => "todo",
            :action => "show_date"

Originally, the 'show_date' action and associated view would display all the activities associated for that day for all the Campaigns.

This ended up being very slow on the database...it would generate roughly 30 records but was still slow.

So, I'm thinking of creating a partial that would first list the campaigns separately.

If someone clicked on a link associated with campaign_id = 1, I want it to go to the following route:

todo/today/campaign/1

Then I would like to know how to know that the '1' is the campaign_id in the controller and then just do its thing.

The reason I want a distinct URL is so that I can cache this list. I have to keep going back to this and it's slow.

NOTE: It's possibly the problem actually is that I've written the queries in a slow way and sqlite isn't representative of how it will be in production, in which case this work-around is unnecessary, but right now, I need a way to get back to the whole list quickly.

like image 212
Satchel Avatar asked Dec 03 '25 09:12

Satchel


1 Answers

The code above by @Damien is correct but incomplete. It should be:

map.todo "todo/today/campaign/:id", :controller => "todo", :action => "show_date"

in your views all you have to do is:

<%= link_to "Campaign 1", todo_path(:id => 1) %>

or simply

<%= link_to "Campaign 1", todo_path(1) %>

and the particular campaign id can be fetched using params[:id] in your action.

And yeah, sqlite is not production ready.

EDIT: The latter part is quite easy to implement:

However, you have to change the route slightly, The route will now become,

map.todo "todo/today/:campaign/:id", :controller => "todo", :action => "show_date"

in your views:

<%= link_to "Campaign 1", todo_path(:campaign => "campaign", :id => 1) %>

In your todo controller, show_date action:

def show_date

#IF YOU ARE USING THIS REPEATEDLY IN LOTS OF DIFFERENT ACTIONS THEN A BETTER PLACE FOR THIS WOULD BE AS A HELPER IN application_controller.rb

 if params[:id].nil? && params[:campaign].nil?
    #DO SOMETHING WHEN BOTH ARE NIL,
 elsif params[:campaign]!="campaign"
    #DO SOMETHING WITH CAMPAIGN BEING SOMETHING OTHER THAN "CAMPAIGN"
 elsif params[:campain]=="campaign" && params[:id].nil?
    #DO SOMETHING WITH ID BEING NIL.
 else
    #FIND YOUR CAMPAIGN HERE.
 end
end

Hope this helps. :)

like image 82
2 revsShripad K Avatar answered Dec 04 '25 23:12

2 revsShripad K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!