ruby-on-railsruby-on-rails-3associationshas-many

How to define dynamic has_many relationship depending on if another model/table exists in Rails 3.2.12?


There are customers and projects model in our Rails app. However project model may or may not present along with the customer model. Their relationship are:

class Project
  belongs_to :customer, :class_name => 'Customer'
end

class Customer
  has_many :projects, :class_name => 'Project', :conditions => if projects model exists
end

Basically we would like to make the has_many in customer model dynamic depending on if the project model exists. Is this something doable in Rails 3.2.12?


Solution

  • I'm not sure I follow. If you need to have a dynamic association based on if the associated class is defined, then you'd write something along these lines:

    class Customer
       if defined? Project
          has_many :projects, :class_name => 'Project'
       end
    end
    

    If you meant a model like an object or record in database, then I'm not sure why the association can't stay where it is.

    Update

    Yes you can do that in one line. But take caution, that this woun't work as expected in development environment, since config.cache_classes is set to false, the 'defined? Project' will always return nil unless you explicitly call it.

    If you need to test this behaviour then set config.cache_classes = true in your development.rb ( note that this will ignore code changes unless you restart your server ).

    class Customer
       has_many :projects, :class_name => 'Project' if defined? Project
    end