简体   繁体   中英

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 site, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM