Friday, 16 November 2012

a theoretical problem with rails models

so let's say you have model 1: Locations
and you have model 2: Phones

You can't have a Location without at least a Phone and vice versa. Now let's say you only need a Phone for certain Location. Like for example a Post Office needs a Phone. But a private home doesn't really need one. What do you do:

class Locations < ActiveRecord::Base
                    has_many: Phones
                   validates: phone, :presence => true, :if => Proc.new {|location| location.needs_phone?}

   
          class Phones < ActiveRecord
                     belongs_to: Locations



Now the real problem comes at the specs. Here is what i discovered you can do

factory :locations do 
                trait :phone do
                     phone { FactoryGirl.create(:phone, :location_id => self) }
                end

          factory :phones do
               associations :locations


What i usually discovered is that when people look for a particular solution for they're problem you usually need bits and peaces from other people code. Maybe it will help you in a similar situation. I do understand that there can be made an argument that the models weren't thought out correctly and there can be a million other better solution.

A similar solution is you can put an after :build and then create the phone there. Or you can create the location as one that doesn't need a phone and then add the phone and switch to a phone required location.

 

0 comments:

Post a Comment