I am trying to create a has_many :through association so that my Users can keep track of Domains by creating the association when they add them on their account page.
I have the following models:
models/user.rb
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
has_many :domain_followings, :foreign_key => "domain_id"
has_many :domains, :through => :domain_followings
models/domain_followings.rb
class DomainFollowings < ActiveRecord::Base
attr_accessible :domain_id
belongs_to :user
belongs_to :domain
end
models/domain.rb
class Domain < ActiveRecord::Base
attr_accessible :name
has_many :domain_followings, :foreign_key => "user_id"
has_many :users, :through => :domain_followings
I get errors like the following in my specs:
1) Users signup success should make a new user
Failure/Error: click_button
NameError:
uninitialized constant User::DomainFollowing
# ./app/controllers/users_controller.rb:32:in `show'
# ./spec/requests/users_spec.rb:32
# ./spec/requests/users_spec.rb:26
The code in question is here:
def show
@user = User.find(params[:id])
@title = @user.name
@domain = Domain.new if signed_in?
@domains = @user.domains.paginate(:page => params[:page])
end
The uninitialized constant User::DomainFollowing is repeated several times for other code.
Ideally I would like my code to require a user association in the domain_followings table before allowing a domain to be created in the domain table. Is this possible?
Solution was to rename the relationship model to models/domain_following.rb, making it singular. Also removed foreign_key declarations following Bladrick’s suggestion. Everything flows smoothly now.