Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record with Delegate and conditions

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 
like image 607
Fousa Avatar asked Nov 12 '09 10:11

Fousa


People also ask

What is meant by active record?

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.

What is delegate in Rails model?

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.

What is non active record?

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.

What are scopes in Rails?

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.


1 Answers

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 
like image 77
Simone Carletti Avatar answered Oct 03 '22 16:10

Simone Carletti