read

We all know that rails models associations gets defined while class definitions are loaded and once defined can’t be changed.

But still you can make use of block parameter to conditions to have dynamic query conditions inside associations.

Below line explains how to define dynamic associations :

<div class='code-highlight'><pre class='code-highlight-pre'><div data-line='1' class='code-highlight-row numbered'><div class='code-highlight-line'>has_one :code_sequence, :class_name => 'Sequence', :conditions => 'kind = "#{self.kind}"'</div></div></pre></div>

Please make a note that below code will not work :

<div class='code-highlight'><pre class='code-highlight-pre'><div data-line='1' class='code-highlight-row numbered'><div class='code-highlight-line'>has_one :code_sequence, :class_name => 'Sequence', :conditions => proc { |c| ['kind = ?', c.kind] }</div></div></pre></div>

Blog Logo

Sandip Ransing


Published

Image

Fun On Rails

Journal of a Web Developer #ruby #rails #JS

Back to Overview