使用@ blog.user.followers.build进行未初始化的常量User :: relationship

时间:2012-01-24 11:07:26

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

以下代码可以正常运行:

  = 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

1 个答案:

答案 0 :(得分:4)

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

:class_name => 'Relationship' 
你仍然遇到问题吗?对于我认为的类名,这应该是正确的情况。