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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With