Search code examples
ruby-on-railsvariableslink-tocontrollers

Sending a variable through a link_to without url query in Ruby on Rails


I'm trying to send a variable through a link_to, without using url query in Ruby on Rails, from one controller's index view to be used on another controller's index.

Basically, I need to pass the Turma.id (school class id), to the Elementos_turma(peoples in the class) controller, so I can use it and filter the index: ElementosTurma.find(:all, :conditions => { :turma_id => xxxxx } ), to show the peoples of the selected class.

It it possible? Maybe without using a session variable? Maybe sending the variable to a method on the 1st controller, to send it the other controller? (if so how? not very RoR wise... :) )


Solution

  • No need for a special method to get the info you need, the magic of routes will do.

    In your routes.db file, you should be able to define something like this,

    map.resources :class, :has_many => :students
    

    Then if you run 'rake routes' you should see a routes similar to this

    class_students GET /classes/:class_id/students(.:format)  {:controller=>"students", :action=>"index"}
    

    You can call that path in your view like so

    class_students_path(class_id)
    

    Then in your controller you will have access to params[:class_id]

    The name of the route isn't very pretty, but this should work.

    EDIT--------------------------------------

    According to your comment, you can't use map.resources for some reason or another...

     map.class_students '/:class_id/students', :controller => 'students', :action => 'index'
    

    That will produce the same route available in your view, same param in your controller.

    That being said, I don't know how a server bug could prohibit you from using map.resources