Sinatraでアソシエーションモデルを構築したいと思って、
@user = User.create(user_serial:"h1ga2") @post1 = @user.posts.build
でエラーが出て、NoMethodError - undefined method posts for #<User id: 1, user_serial: "h1ga2">
と出ます。
schema.rbは以下の通りです。
ActiveRecord::Schema.define(version: 20170828125411) do create_table "posts", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| t.string "content", null: false t.bigint "users_id" t.index ["users_id"], name: "index_posts_on_users_id" end create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| t.string "user_serial", null: false end end
またmigrationファイルは以下の通りです。
class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.string :user_serial, :null => false t.timestamp end end end
class CreatePosts < ActiveRecord::Migration[5.1] def change create_table :posts do |t| t.string :content,:null=>false t.belongs_to :users, :index=>true t.timestamp end end end
です。モデルは
class User < ActiveRecord::Base has_many :posts, dependent: :destroy end class Post < ActiveRecord::Base belongs_to :user end
です。どうしてうまくいかないのでしょうか。
よろしくお願いいたします。
あなたの回答
tips
プレビュー