I am working on a Rails app where a User can create a magazine and another user can subscribe to that magazine. I want to know the best way to do this.
Currently I have a subscription model that builds from current user when created and users the current magazine as the magazine_id. This allow me to have a table of user_ids and magazine_ids. This allows me to see all the subscriptions but it means I cant easily check all the magazines someone subscribes to or check all the subscribers of a magazine.
When I try to use has_many :through, it throws up an error with building from current user. I have put in the relevant code below, hopefully it covers it all and thanks in advance.
User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :magazines
has_many :subscriptions
end
Subscription model:
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :magazine
end
Magazine model:
class Magazine < ActiveRecord::Base
belongs_to :user
has_many :subscrptions
has_many :users
end
The snippet of code from the subscription controller that throws up the error when I use has many through
def new
@subscription = current_user.subscriptions.build
@sub = Sub.find(params[:sub_id])
end
Hopefully that is enough for someone to figure out, if not please ask me for the other code or information.
Aucun commentaire:
Enregistrer un commentaire