Skip to content

Instantly share code, notes, and snippets.

@markfeedly
Created June 28, 2014 16:09
Show Gist options
  • Save markfeedly/e835c9e157134c2431a6 to your computer and use it in GitHub Desktop.
Save markfeedly/e835c9e157134c2431a6 to your computer and use it in GitHub Desktop.
OK Ive created a Subscription model, and expect somewhat to hang stuff off there
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :page
end
There is an indexed id in the table cause I created it thus
class CreateSubscriptionsTable < ActiveRecord::Migration
def change
create_table :subscriptions do |t|
t.integer :page_id
t.integer :user_id
end
add_index :subscriptions, :page_id
add_index :subscriptions, :user_id
end
end
---------------
class User #...
has_many :subscriptions
has_many :pages, through: :subscriptions
----------------
class Page # ..
has_many :subscriptions
has_many :users, through: :subscriptions
def subscribe(usr)
self.users << usr unless self.users.exists?(usr)
end
-------------------
Failing test, note creating a page adds the page creator to the subscribers (currently, the users) for a page
describe 'Subscription' do
let(:user) {FactoryGirl.create(:user) }
let(:user1) {FactoryGirl.create(:user) }
let(:page){ FactoryGirl.create(:page, title: 'first title', user: user, content: 'any' ) }
it "should keep track of subscribed pages for several users" do
user.pages.should == [page]
user1.pages.should == []
page.subscribe(user1)
page.users.should == [user, user1]
user.pages.should == [page]
user1.pages.should == [page] # <------------ fails here
end
expected: [#<Page id: 1, created_at: "2014-06-28 16:00:27", updated_at: "2014-06-28 16:00:27",
slug: "first-title", title: "first title", lock_version: 0, page_type: nil, moscow: "Not set yet">]
got: #<ActiveRecord::Associations::CollectionProxy []> (using ==)
------------------
For reference these low level tests pass:
it "should subscribe page creator" do
page.users.count.should == 1
page.users.last.should == user
end
it "should add a subscriber" do
page.subscribe(user1)
page.users.count.should == 2
page.users.first.should == user
page.users.last.should == user1
end
it "should add a subscriber once only" do
page.subscribe(user)
page.subscribe(user1)
page.subscribe(user1)
page.users.count.should == 2
page.users.first.should == user
page.users.last.should == user1
user.pages.should == [page]
end
---------------
problem 2 I have yet to get something like the following working
class Page # ..
has_many :subscriptions, class_name: :user
has_many :subscribers, through: :subscriptions
no matter which line I put class_name on... but that may be that I need to carefully read documentation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment