[英]How to save class as one of the attributes in ROR model
我試圖在名為chat的rails中創建一個模型,其中有兩列user1和user2,並且我想在其中存儲用戶對象。 在grails中,我只是這樣做
class Chat {
User user1
User user2
Date chatStartedOn
}
我完成了。 我對rails做了一些相同的事情
rails generate model Chat user1:User user2:User chatStartedOn:date
但我運行db:migrate它向我顯示錯誤
undefined method `User' for #<ActiveRecord::ConnectionAdapters::TableDefinition
我的用戶遷移文件
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :encrypted_password
t.string :salt
t.timestamps
end
end
end
請指導我如何將用戶對象保存在聊天表中。
嘗試這個
rails generate migration CreateChats
然后,您可以在聊天遷移文件中添加此代碼
class CreateChats < ActiveRecord::Migration
def change
create_table :chats do |t|
t.integer :user1_id, :references => [:users, :id]
t.integer :user2_id, :references => [:users, :id]
t.date :chatStartedOn
t.timestamps
end
end
end
然后,您需要添加關聯
模型user.rb
has_one :chat
模型chat.rb
belongs_to :user1, :class_name => "User"
belongs_to :user2, :class_name => "User"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.