【问题标题】:I am having this issue, 'NameError: uninitialized constant Profile::friend', when running 'rake db:seed'我在运行'rake db:seed'时遇到了这个问题,'NameError: uninitialized constant Profile::friend'
【发布时间】:2016-02-02 19:14:08
【问题描述】:

控制台错误

/puppyPals 控制台$ rake db:seed 耙中止! NameError: 未初始化的常量 Profile::friend /Desktop/puppyPals/puppyPals/app/models/profile.rb:8:in `follow' /Desktop/puppyPals/puppyPals/db/seeds.rb:31:in `block in ' /Desktop/puppyPals/puppyPals/db/seeds.rb:31:in `each' /Desktop/puppyPals/puppyPals/db/seeds.rb:31:in `

#app/models/profile.rb 类配置文件

    # Follows a profile.
    def follow(other_profile)
        friends.create(followed_id: other_profile.id)
    end

    # Unfollows a user.
    def unfollow(other_profile)
        friends.find_by(followed_id: other_profile.id).destroy
    end

    # Returns true if the current user is following the other user.
    def following?(other_profile)
        following.include?(other_profile)
    end
end

#Seeds.rb
Profile.create!(first_name:  "First",
             last_name: "Last",
             dog_name:  "Dog")

99.times do |n|
    first  = "name-#{n}"
    last = "last"
    dog = "dog"
    Profile.create!(first_name: first,
                 last_name: last,
                 dog_name: dog)
end

profiles = Profile.all
profile  = profiles.first
following = profiles[2..50]
followers = profiles[3..40]
following.each { |followed| profile.follow(followed) }
followers.each { |follower| follower.follow(profile) }

【问题讨论】:

  • class_name 应该是正确的大小写,例如class_name: 'Friend'

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord nameerror


【解决方案1】:

您需要为您的朋友模型正确定义您的class_name。它应该更改为:

class Profile < ActiveRecord::Base
  has_many :friends, class_name:  "Friend", foreign_key: "follower_id",
        dependent:   :destroy
  # ...
end

Read more about the class_name argument here.

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多