Is it possible to use delegate in your Active Record model and use conditions like :if
on it?
class User < ApplicationRecord delegate :company, :to => :master, :if => :has_master? belongs_to :master, :class_name => "User" def has_master? master.present? end end
1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
delegate provides a delegate class method to easily expose contained objects' public methods as your own. Simply say, through delegation you can use public methods in other model directly. For example I have a QueueItem and a Video model.
Inactive records are documents (both hardcopy and electronic) which are no longer referenced on a regular basis and tend to be stored in a less accessible place since they are not used frequently.
Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.
No, you can't, but you can pass the :allow_nil => true
option to return nil if the master is nil.
class User < ActiveRecord::Base delegate :company, :to => :master, :allow_nil => true # ... end user.master = nil user.company # => nil user.master = <#User ...> user.company # => ...
Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.
class User < ActiveRecord::Base # ... def company master.company if has_master? end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With