0

Hey i'm creating database schema and test it in rails console. I have relation User has_many :rates and Rates belongs_to :user. When I type in rails console:

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

Every thing works fine, but when i want to do it in opposite way:

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

I've got an following error NoMethodError: undefined method `<<' for nil:NilClass

Users Migration

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

Rates Migration

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
mkkrolik
  • 1,200
  • 14
  • 21

1 Answers1

0

The user attribute is not an array (or collection of any kind), you must assign to it.

user2 = User.find(2)
rate2 = Rate.find(2)
rate2.user = user2
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52