次の移行とモデルがあります。
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>