簡體   English   中英

如何在Rails應用程序中將模型與用戶模型關聯

[英]How to associate models with User model in rails application

我的Rails應用程序中有兩個模型User和Event,但是在events表中user_id始終為NULL

+----+------------+----------+-------------+---------------------+---------+
| id | date       | time     | venue       | created_at          | user_id |
+----+------------+----------+-------------+---------------------+---------+
|  1 | 0011-11-11 | 12:00:00 | ait pune    | 2015-09-18 11:16:51 |    NULL |
|  2 | 0011-11-11 | 12:00:00 | dighi hills | 2015-09-18 14:29:01 |    NULL |
|  3 | 0011-11-11 | 12:00:00 | obh         | 2015-09-18 14:32:41 |    NULL |
|  4 | 0011-11-11 | 12:00:00 | nbh         | 2015-09-18 14:46:40 |    NULL |
+----+------------+----------+-------------+---------------------+---------+

下面是我的架構

ActiveRecord::Schema.define(version: 20150918134819) do

  create_table "events", force: :cascade do |t|
    t.date     "date"
    t.time     "time"
    t.string   "venue",      limit: 255
    t.integer  "user_id",    limit: 4
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  limit: 255, default: "", null: false
    t.string   "encrypted_password",     limit: 255, default: "", null: false
    end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree

end

用戶和事件模型如下

class User < ActiveRecord::Base
  has_one :event, dependent: :destroy
end

class Event < ActiveRecord::Base
    belongs_to :user
end

我不知道我要去哪里錯了

應該是has_many關聯

class User < ActiveRecord::Base
  has_many :events, dependent: :destroy
end

class Event < ActiveRecord::Base
    belongs_to :user
end

用法

arsen = User.create
arsen.events << Event.create

Event.create(user: arsen)

has_many關聯表示與另一個模型的一對多連接。 您通常會在belongs_to關聯的“另一側”找到該關聯。 該關聯表明該模型的每個實例具有另一個模型的零個或多個實例。 例如,在包含客戶和訂單的應用程序中,客戶模型可以這樣聲明:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM