Sameer A.
Sameer A.

Reputation: 167

Ruby on Rails: Pass request params in controller to model's after_create event

I have two models:

1) Procedure
     title
     document_number

2) Revision
     revision_number

In my procedure model, I defined a method after_create to automatically create a Revision with revision_number set to 0.1.

# app/models/procedure.rb

# How do I get revision_number from the request params in this method?
after_create do |procedure|
    procedure.revisions.create(revision_number: 0.1)
end

That works well, however, I do not want to always default to 0.1 - For example, if I want to specify a revision number from parameters sent in the form request to the controller, I am a bit lost there. I looked throughout the guides and I wasn't able to find a way to pass data into the create event. This is my method in my controller:

# app/controllers/procedures_controller.rb

def create
    @procedure = current_user.procedures.build(procedure_params)

    if @procedure.save
        render json: @procedure, status: :created, location: @procedure
    else
        render json: @procedure.errors, status: :unprocessable_entity
    end
end

def procedure_params
    params.require(:procedure).permit(:title, :document_number, :revision_number)
end

The only way I can think of accomplishing this is by adding a column 'revision_number' to my procedure model, and then checking whether it is set in my 'after_create' method.

I would appreciate any other suggestions for how I might be able to tackle this problem. Or if there is already a way and I missed it in the guides, I would appreciate a reference to that section. Thanks!

Upvotes: 0

Views: 2569

Answers (2)

puneet18
puneet18

Reputation: 4427

app/models/procedure.rb

attr_accessor :revision_no

after_create do |procedure|
    procedure.revisions.create(revision_number: self.revision_no)
end

Now you can pass value in revision_no.

Upvotes: 1

Mihir Kumar Thakur
Mihir Kumar Thakur

Reputation: 393

you are trying to violate MVC architecture and Single Responsiblity Principle. Controller is responsible for handling HTTP request and Model is responsible for interacting with database.

In any case you commited to violate rules :-

class Procedure < ActiveRecord::Base
  def add_revision_number(number)
    self.revision_number = number
  end
end

class ProceduresController < ApplicationController
  def create
    ...
    @procedure.add_revision_number(params[:revision_number])
    ...
  end
end

now access revision_number in model

I prefer not to pass controller request object directly. It Isolates model from current request.

Upvotes: 1

Related Questions