Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
How to get url params in observer or model in Rails 3.1
2 Posts
How to get url params in observer or model in Rails 3.1

Hi, I need to get/use URL params in Rails 3.1 Observer or Model. I know url params can be passed from controller to model but I actually need to get directly(like $_REQUEST['p1'] in php MVC codeigniter model) params in model. If it is possible, please help me.

Person
Forum Rating: 100
Sign In To Rate Post

You can do some modifications in application.rb file to get params model instead of controller. Add the following code in application.rb file to get the result.

class ApplicationController < ActionController::Base # Your existing stuff around_filter :you_dont_have_bloody_clue protected def you_dont_have_bloody_clue

 klasses = [ActiveRecord::Base, ActiveRecord::Base.class]
 methods = ["session", "cookies", "params", "request"]
 methods.each do |shenanigan|
   oops = instance_variable_get(:"@_#{shenanigan}")
   klasses.each do |klass|
     klass.send(:define_method, shenanigan, proc { oops })
   end
 end
 yield
 methods.each do |shenanigan|
   klasses.each do |klass|
     klass.send :remove_method, shenanigan
   end
 end

end end

However it is not recommended to do so in rails. Best way to call params is through controllers and not in model. In php it can be done through models. Even though it is possible but that wouldn't be rails way. So use controllers for that. Normally whatever params are declared in controller, are taken directly by the model, that is the way rails works. Accessing params from model is possible but that will be kind of hacking into the default way of working of rails.

2 Posts
Login to add your message