Ramiz Raja
Ramiz Raja

Reputation: 6030

Activerecord relationships

I have following modles in my application..

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

My requirement is that a user can subscribe to many posts and i want to use has_many :through relationship, as i want to have an extra attribute subscription_type in joining table. User has many to many relationship with post.

Please tell me the best way to do this.

Upvotes: 0

Views: 95

Answers (1)

Matzi
Matzi

Reputation: 13925

Quite simple:

class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :posts, :trough => :subscriptions
end

class Subscription< ActiveRecord::Base
  belongs_to :user
  belongs_to :post

  # add subscription_type to db columns
  # also user_id and post_id
end

class Post < ActiveRecord::Base
  has_many :subscriptions
  has_many :users, :trough => :subscriptions
end

Upvotes: 2

Related Questions