user1573607
user1573607

Reputation: 522

Rails - has_many relation causes NoMethodError

I've the following migrations and models:

class CreatePlatforms < ActiveRecord::Migration
  def change
    create_table :platforms do |t|

        t.integer :user_id
        t.string :name
        t.string :platform_id
        t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|

        t.string :email
        t.string :first_name
        t.string :last_name
        t.string :gender
        t.date :birthday
        t.timestamps
    end
  end
end

class Platform < ActiveRecord::Base
    belongs_to :user
end

class User < ActiveRecord::Base
    attr_accessible :email, :first_name, :last_name, :gender, :birthday
    has_many :platforms
end

With this definition I can create users and platforms:

user = User.new
platform1 = Platform.new
platform2 = Platform.new

And even I can associate users to platforms:

platform1.user = user

But when I try to associate platforms to users or get the platforms from a users it crashes:

user.platforms << user or user.platforms
NoMethodError: undefined method `platforms' for #<User:0x007f8cfd47a770>

Upvotes: 1

Views: 562

Answers (1)

davegson
davegson

Reputation: 8331

As it turns out, the problem is the database field platform_id. This messes up rails. Simply delete it and it'll work.

Upvotes: 3

Related Questions