【发布时间】:2012-03-04 08:32:19
【问题描述】:
我正在尝试创建一个 has_many :through 关联,以便我的用户可以通过在他们的帐户页面上添加域时创建关联来跟踪域。
我有以下型号:
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
我的规范中出现如下错误:
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
有问题的代码在这里:
def show
@user = User.find(params[:id])
@title = @user.name
@domain = Domain.new if signed_in?
@domains = @user.domains.paginate(:page => params[:page])
end
未初始化的常量 User::DomainFollowing 对其他代码重复多次。 理想情况下,我希望我的代码在允许在域表中创建域之前需要在 domain_followings 表中进行用户关联。这可能吗?
【问题讨论】:
-
我不认为这是相关的,但我对用户和域中的指令
has_many :domain_followings的:foreign_key声明感到困惑。在我看来,它们是倒置的(如果不是故意的,它应该被删除)。 -
这导致保存关系出现问题。我也遇到了问题,因为这种关系的模型是复数而不是单数。我修复了这些问题,现在效果更好了,但很多功能仍然存在问题。
标签: ruby-on-rails has-many-through