【问题标题】:uninitialized constant User::relationship using @blog.user.followers.build未初始化的常量 User::relationship 使用 @blog.user.followers.build
【发布时间】:2012-01-24 11:07:25
【问题描述】:

以下代码可以正常工作:

  = form_for @blog.comments.build, :remote => true do |f|

但是,下面会导致错误“未初始化的常量 User::relationship”:

  = form_for @blog.user.followers.build do |f|

用户模型声明如下:

class User < ActiveRecord::Base
  has_many :blogs
  has_many :comments

  has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy
  has_many :reverse_relationships, :foreign_key => "followed_id",
                                   :class_name  => "relationship",
                                   :dependent   => :destroy

  has_many :following, :through => :relationships, :source => :followed
  has_many :followers, :through => :reverse_relationships, :source => :follower
end

为什么第一个例子有效但第二个无效?

编辑: 博客模型:

class Blog < ActiveRecord::Base
  belongs_to :user
  has_many :comments

end

关系模型:

class Relationship < ActiveRecord::Base
  attr_accessible :followed_id

  belongs_to :follower, :class_name => "User"
  belongs_to :followed, :class_name => "User"

  validates :follower_id, :presence => true
  validates :followed_id, :presence => true

  validate :validate_followers

  def validate_followers
    errors.add(:follower_id, "You cannot follow yourself") if follower_id == followed_id
  end
end

【问题讨论】:

  • 能否请您展示您的博客模型?博客是否只有一个用户?
  • 这是“has_many :blogs”而不是“has_many :users”吗?
  • @timbrandes 是的,每个博客只有一个用户
  • @BenB thx,已修复。但是同样的错误。
  • 如果您将反向关系上的 :class_name 选项更改为 `=> 'Relationship',您还会遇到问题吗?我相信它应该是类名的正确大小写。

标签: ruby-on-rails foreign-keys rails-models


【解决方案1】:

如果您将反向关系上的 :class_name 选项更改为:

:class_name => 'Relationship' 

你还有问题吗?我相信它应该是类名的正确大小写。

【讨论】:

  • 在我的例子中,它写的是:class_name =&gt; 'Relationships'而不是:class_name =&gt; 'Relationship'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
相关资源
最近更新 更多