ruby - Create a rails controller which will update multiple tables in db -
ruby - Create a rails controller which will update multiple tables in db -
i new rails. can create 1 controller take json info , update multiple table in db? contoller nuthing in view.
i doing following:- routes.rb:
post '/data' => 'data#submit'
app/controllers/data_controller.rb:
class datacontroller < applicationcontroller def submit info = json.parse request.body.read puts info end end
then sending post request,
restclient.post "localhost:3000/submit_result", data.to_json, {:content_type => :json}
but gving error
actioncontroller::routingerror (uninitialized constant datacontroller)
you need create route in config/routes.rb it.
if have action, definition like
resource :data, only: [] post :submit end
only: []
=> makes default crud actions not beingness created.
then in controller can following:
class datacontroller < applicationcontroller def submit info = json.parse params[:some_key] puts info render nothing: true # avoid view rendering end end
your rest client should phone call this:
restclient.post "localhost:3000/data/submit", data.to_json, {:content_type => :json}
about if can update multiple tables controller: yes, possible.
suppose send info next format:
restclient.post "localhost:3000/data/submit", {user: {name: 'john'}, role: {name: 'admins'} }.to_json, {:content_type => :json}
then, in controller create user , role, based on received params:
class datacontroller < applicationcontroller def submit user.create params[:user] role.create params[:role] render nothing: true # avoid view rendering end end
anyway might complicate controller's code. best approach create new class receiving params , creatign stuff need.
class datacontroller < applicationcontroller def submit massdatacreator.create(params) render nothing: true # avoid view rendering end end
the benefit of controller code looks clearer, , can write unit tests new class creates info (it's easier test single class unit testing controller through integration tests)
ruby-on-rails ruby ruby-on-rails-4
Comments
Post a Comment