Set a field in all models

Asked

Viewed 43 times

0

I’m trying to create an app that works with several companies and I always need to record the field company_id whenever creating and/or updating any model, what’s the best way to do this?

I thought of a before_action throughout models, but I get one

undefined method `before_action' for #<Class:0x007fcfd9438d38>

One of the models is this:

class Config < ApplicationRecord
  before_action :set_current_user

  def set_current_user
    User.current = current_user
  end

  belongs_to :company

validates :company_id, uniqueness: true

  dragonfly_accessor :logo

  before_save :set_company

  private
    def set_company
      self.company_id = current_user.company_id
    end
end
  • Good afternoon, you can post the Model code?

  • Actually, looking at your code, you’re using a before_save for this purpose. Right? But the error comes from before_action, as you said? What would be the logic of your method set_current_user ? You are setting an attribute current in class User. Does this attribute exist in the User model? Can you elaborate a little more? your before_save seems OK

  • the set_current_user comes from Vise, but it is not available in models, and the company_id already recorded in the registered user section, so I thought to use this to set in all methods, since each user must have only data of your company.

  • The code above seems to be OK, what error returns from it? Tried to simulate an insertion by the console?

  • Both in the browser and in the console I receive the message Config.find_by_company_id(1)&#xA;NoMethodError: undefined method before_action' for #<Class:0x00000008adea78> Did you Mean? before_commit from /home/Adell/. rvm/Gems/ruby-2.3.3/Gems/activerecord-5.0.1/lib/active_record/dynamic_matchers.Rb:21:in method_missing'

  • Try to replace that one first before_action for before_save, since before_action is a controller callback, not a model callback. Your before_save of set_company that you quoted in the question seems ok.

  • That’s right, the problem apparently is before_action should not be used in the model.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.