Rails - has_many关系导致NoMethodError

时间:2013-11-02 10:33:07

标签: ruby-on-rails ruby model associations has-many

我有以下迁移和模型:

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

通过这个定义,我可以创建用户和平台:

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

甚至我可以将用户关联到平台:

platform1.user = user

但是,当我尝试将平台与用户关联或从用户那里获取平台时,它会崩溃:

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

1 个答案:

答案 0 :(得分:3)

事实证明,问题是数据库字段platform_id。这搞砸了铁轨。只需删除它就可以了。