title: Rails finding model in other model's method
body: <p>I would like to implement a server side validation for the following:
  Subscriptions for a certain posting can only be created as long as the number of subscriptions doesn't exceed the number of spots for this posting.  </p>
  
  <pre><code>    class Cposting &lt; ActiveRecord::Base
        belongs_to :user 
        has_many :subscriptions, 
                  foreign_key: "post_id", 
                  dependent: :destroy
  ...
  
      def spots_left #returns the number of places left in this class
        self.spots.to_i - Subscription.where(post_id: self.id).count.to_i
      end
  ...
  end
  </code></pre>
  
  <p>In the Subscription model I tried to call the spots_left method to determine whether there are any spots left for the Cposting a new subscription belongs to. </p>
  
  <pre><code>class Subscription &lt; ActiveRecord::Base
      belongs_to :subscriber, class_name: "User"
      belongs_to :post, class_name: "Cposting"
  
      ...
      validate :class_not_full
  
  
  
  def class_not_full
      Cposting.find_by(id: self.post_id).spots_left &gt; 0 
  end
  end
  </code></pre>
  
  <p>Running tests on the Subscription model returned a nil error </p>
  
  <pre><code>NoMethodError: undefined method `spots_left' for nil:NilClass
  </code></pre>
  
  <p>It seems I can not use find_by, find or where methods to point to this Cposting. </p>
  
  <p>I would like to know how to refer to the Cposting that belongs to the Subscription being validated, or an alternative way to implement this validation. </p>
  
  <p>Thanks</p>
  
  <p>EDIT adding tests</p>
  
  <pre><code>require 'test_helper'
  
  class SubscriptionTest &lt; ActiveSupport::TestCase
    def setup
      @cposting = cpostings(:one) #has one spot
      @customer = users(:customer)
      @customer2 = users(:customer2)
      @subscription = Subscription.new(post_id: @cposting.id, subscriber_id: @customer.id)
  end
  
  ...
  
    test "subscriptions cannot exceed spots" do
      @subscription.save
      assert @cposting.subscriptions.count == @cposting.spots 
      @subscription2 = Subscription.new(post_id: @cposting.id, subscriber_id: @customer2.id)
      assert_not @subscription2.valid?
    end
  
  end
  </code></pre>
  
  <p>Running <code>rake test TEST=test/models/subscription_test.rb</code> gives</p>
  
  <pre><code>  1) Failure:
  SubscriptionTest#test_subscriptions_cannot_exceed_spots [/~/test/models/subscription_test.rb:37]:
  Expected true to be nil or false
  
  5 runs, 7 assertions, 1 failures, 0 errors, 0 skips
  </code></pre>
  
  <p>EDIT 2 adding create method</p>
  
  <pre><code>class SubscriptionsController &lt; ApplicationController
      def create 
          @posting = Cposting.find(params[:post_id])  
          current_user.subscriptions.create(post_id: @posting.id)
          flash[:success] = "Subscribed!"
          redirect_to subscriptions_path
      end
  end
  </code></pre>