Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you want is a many to many relationship between User and Feed.</p> <p>You'll want something like this in your code for the User and Feed relationship to work.</p> <pre><code>class User &lt; ActiveRecord::Base has_and_belongs_to_many :feeds end class Feed &lt; ActiveRecord::Base has_and_belongs_to_many :users end </code></pre> <p>You can read more about this in the Rails Guides - <a href="http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association" rel="nofollow">http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association</a></p> <p>You may also want to look at using has_many :through with an intermediate model for this (explained here <a href="http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many" rel="nofollow">http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many</a>) if you'd like to store any meta data for a user-feed relationship record.</p> <p>Edit: I managed to get a similar setup working on 3.0 as well as 3.1 (using has_many :through).</p> <p>Here are the contents of my models.</p> <pre><code>➜ app cat app/models/* class Cast &lt; ActiveRecord::Base belongs_to :feed end class Feed &lt; ActiveRecord::Base has_many :subscriptions has_many :casts end class Subscription &lt; ActiveRecord::Base belongs_to :user belongs_to :feed end class User &lt; ActiveRecord::Base has_many :subscriptions has_many :feeds, :through =&gt; :subscriptions # For 3.1 has_many :casts, :through =&gt; :feeds # For 3.0 def casts Cast.joins(:feed =&gt; :subscriptions).where("subscriptions.user_id" =&gt; self.id) end end </code></pre> <p>and here are the migrations I used</p> <pre><code>➜ app cat db/migrate/* class CreateUsers &lt; ActiveRecord::Migration def self.up create_table :users do |t| t.string :name t.timestamps end end def self.down drop_table :users end end class CreateFeeds &lt; ActiveRecord::Migration def self.up create_table :feeds do |t| t.string :name t.timestamps end end def self.down drop_table :feeds end end class CreateCasts &lt; ActiveRecord::Migration def self.up create_table :casts do |t| t.string :name t.integer :feed_id t.timestamps end end def self.down drop_table :casts end end class CreateSubscriptions &lt; ActiveRecord::Migration def self.up create_table :subscriptions do |t| t.integer :feed_id t.integer :user_id end end def self.down drop_table :subscriptions end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload