undefined 方法 '<<' for nil:NilClass rails console



嘿,我正在创建数据库模式并在 Rails 控制台中对其进行测试。我有关系 用户has_many :费率费率 belongs_to :用户。当我在轨道控制台中输入时:

user = User.find(1)
rate = Rate.find(1)
user.rates << rate

每件事都很好,但是当我想以相反的方式做时:

user2 = User.find(2)
rate2 = Rate.find(2)
rate2.user << user2

我有一个以下错误 NoMethodError:nil:NilClass 的未定义方法 '<<'

用户迁移

class CreateUsers < ActiveRecord::Migration
  def up
    create_table :users do |t|
      t.column "username", :string, :limit => 25 
      t.string "first_name", :limit => 30
      t.string "last_name", :limit => 50
      t.string "password" 
      t.date "date_of_birth" 
      t.timestamps
    end
  end
end

费率迁移

class CreateRates < ActiveRecord::Migration
  def change
    create_table :rates do |t|
      t.integer "user_id"
      t.integer "credibility", :limit => 1 #0 or 1
      t.timestamps
    end
    add_index("rates", "user_id")
  end
end

user 属性不是数组(或任何类型的集合),您必须分配给它。

user2 = User.find(2)
rate2 = Rate.find(2)
rate2.user = user2

相关内容

最新更新