ruby on rails - Add custom field from foreign table and validate it -
i have 2 models, user model , agent model. user has one/zero agent. each agent has "code" promo code.
when user signs up, can optionally enter agent code. when checking form, if user enters code, have check based on table "agents."
if code wrong, form not validated , error appears, if code correct associate user agent.
user model (user.rb)
class user < activerecord::base enum role: [:user, :vip, :admin] after_initialize :set_default_role, :if => :new_record? has_one :agent def set_default_role self.role ||= :user end devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable end agent model (agent.rb)
class agent < activerecord::base belongs_to :user end migration between user , agent
class addagenttousers < activerecord::migration def change add_reference :users, :agent, index: true add_foreign_key :users, :agents end end user db
- id
- password,encrypted_password,...
- sign_in information (time,ip,...)
- agent_id
agent db
- id
- code
- name
how should this?
may you,
in user model add 1 attribute called code.
attr_accessor :code and validate :code on create like, agent present expected code.
validates :code_validation, on: :create def code_validation c = agent.find_by_code(code) if c.present? self.agent = c else errors.add(:code, "agent not found code") end end
Comments
Post a Comment