How do you pass parameters to a controller method when you invoke it in the Rails console?

Viewed 8260

I'm using Rails 5. I have this controller ...

class MyObjectsController < ApplicationController

  def create
    my_object = MyService.build(create_params)

I would like to call the create method in the rails console but I get this error ...

irb(main):007:0> MyObjectsController.new.create(:id => "abc")
Traceback (most recent call last):
        2: from (irb):7
        1: from app/controllers/my_objects_controller.rb:4:in `create'
ArgumentError (wrong number of arguments (given 1, expected 0))

How do I pass parameters to my controller method?

5 Answers

You're getting this error because the create method doesn't receive any argument. In order to use the create action properly you need to pass the ActionController::Parameters to your controller's instance:

c = MyObjectsController.new
c.params = ActionController::Parameters.new(id: "abc")
c.create # It will not work if this controller uses authentication

If the requirement is to call action method of a controller having request method as POST via rails console and pass parameters in it, then it can be done via following commands

# Request any of the application resource, for example root url to get authenticity token
app.get '/'
token = app.session[:_csrf_token]

# parameters to send
parameters = { my_object: { field_one: 'foo', field_two: 'bar' }, authenticity_token: token }

# Call controller method
app.post '/my_objects', params: parameters

You can try

app.post "?create_params[id]=abc"

For example

app.post '/users?user[name]=test&user[age]=20'

will pass the following {"user"=>{"name"=>"test", "age"=>"20"}}

params in Rails can't access everywhere. Params in Rails can only access from class inherited from ActionController::Base, so in Rails console you cannot access your params, but you can access params via a public method.

You can define your controller action as follows:

def my_actions(myparams=nil)
  @loginid = myparams.nil? ? params[:login_id] : myparams[:login_id] 
end

This way you can test your controller in rails console by passing your params.

Related