Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 288
satish Avatar asked Oct 01 '19 20:10

satish


2 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
like image 81
Manoel M. Neto Avatar answered Oct 16 '22 06:10

Manoel M. Neto


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
like image 1
Muhammad Ahmad Avatar answered Oct 16 '22 05:10

Muhammad Ahmad