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?
– mrlew
Actually, looking at your code, you’re using a
before_save
for this purpose. Right? But the error comes frombefore_action
, as you said? What would be the logic of your methodset_current_user
? You are setting an attributecurrent
in classUser
. Does this attribute exist in the User model? Can you elaborate a little more? yourbefore_save
seems OK– mrlew
the
set_current_user
comes from Vise, but it is not available in models, and thecompany_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.– Adell
The code above seems to be OK, what error returns from it? Tried to simulate an insertion by the console?
– mrlew
Both in the browser and in the console I receive the message
Config.find_by_company_id(1)
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:inmethod_missing'
– Adell
Try to replace that one first
before_action
forbefore_save
, sincebefore_action
is a controller callback, not a model callback. Yourbefore_save
ofset_company
that you quoted in the question seems ok.– mrlew
That’s right, the problem apparently is
before_action
should not be used in the model.– Adell