2

下面的代码可以正常工作:

  = 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
4

1 回答 1

4

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

:class_name => 'Relationship' 

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

于 2012-01-25T15:37:12.293 回答