Rails 3 Attaching Model ID to every link
My application centers around an event and specifically the event's ID. Whenever a user navigates to different sections (controllers) of the s开发者_如何转开发ite, I need to be able to carry the event's ID with it.
I'm guessing including the event's ID in the URL is the preferred method in case a user opens multiple browser windows.
I don't want to manually append the event's ID to every link. Is there a helper method I could create to do this for me?
Thanks
You need to create a nested resource in your routes file, this will add something like "/event/#eventid" to the beginning of your path. You can then access this from your controllers with params[:event_id]
eg:
routes.rb
resources :events do
# Other controllers routes go here
end
controller_whatever.rb
def index
@whatever = Event.find(params[:event_id]).whatever.all
end
...
Obviously it would be best to use a before filter, but you get the idea.
You should store that in session data:
session[:event_id] = event_id
You will then be able to access that throughout the user's session.
UPDATE:
You may want to have a look at nested resources.
I recommend to use thomasfedb's solution. If it isn't possible for any reason you could do it by overwriting the url_for method like in this question
精彩评论