Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access params[] when using a callback on model

I'm using the callback before_update to call a function on model which set the checkbox value on my variable.

The problem is the checkbox value which is on params[:mail_checker_issue] isn't accessible on the model layer.

The question is: How to access this params using the callback before_update ? Below my code:

module IssueSetChecketIssuePatch
  def self.included(base)
    base.send(:include, InstanceMethods)
       base.class_eval do
        before_save :before_mail_checker
      end
  end
end

module InstanceMethods
  require_dependency 'issue'
  def before_mail_checker
    self.set_mail_checker_issue(params[:mail_checker_issue]) 
  end

      def set_mail_checker_issue(mail)
      @mail_checker = mail
    end

    def get_mail_checker_issue
      @mail_checker
    end
end 

Rails.configuration.to_prepare do
  Issue.send(:include, IssueSetChecketIssuePatch)
end
like image 538
kamusett Avatar asked Aug 06 '26 04:08

kamusett


1 Answers

params are a controller concern and are wholly separate from models. Consider what should happen if you tried to save that model from a console, for example.

You need to pass the param to the model after you instantiate it from your controller, then check the value set on the model in your before_save callback.

It's also worth noting that your code is somewhat un-Rubyish (and really, looks a lot like Java!) - you could get the same effect by just defining an attr on the model.

Rails.configuration.to_prepare do
  require_dependency 'issue'
  class Issue
    attr_accessor :mail_checker_issue
  end
end

Then, once you have an issue:

# Controller code
@issue = Issue.find(params[:id])
@issue.mail_checker_issue = params[:mail_checker_issue]
like image 162
Chris Heald Avatar answered Aug 08 '26 21:08

Chris Heald