0
我有3個模型:黑客,投票,用戶。如何正確建立我的模型關係
用戶可以創建很多黑客。 每個用戶都應該能夠對每個黑客進行一次投票(評級爲1-5。如果發生錯誤或其他情況,評級應該是可更新的)。
我想到了以下關係: Hack.rb
belongs_to :user
User.rb
has_many :hacks
Votes.rb
belongs_to :user
belongs_to :hack
那是正確的還是我失去了一些東西? 我想過讓所有的票這樣以後:
Hack.first.votes
什麼樣的外國鍵做我必須設置的? 在我的schema.rb中,我已經成功地將我的用戶設置爲< => hack關係,沒有任何外鍵。
ActiveRecord::Schema.define(version: 20141019161631) do
create_table "hacks", force: true do |t|
t.string "url"
t.string "name"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "email", null: false
t.string "crypted_password", null: false
t.string "salt", null: false
t.datetime "created_at"
t.datetime "updated_at"
t.integer "role"
end
end
非常感謝您提前!
非常感謝。這些關係聽起來合理。你知道Rails是否要求我手動設置這些外部列,或者如果belongs_to/has_many roptions爲我做了這些嗎? – 2014-10-19 20:03:26
我發現了一個錯誤。用你的答案黑客has_many用戶,但一個黑客應該只分配給一個用戶。一個用戶,但是,可以創建很多黑客。這意味着 用戶has_many:黑客。 用戶has_many:票數 黑客belongs_to:用戶 黑客has_many:票數通過:用戶 – 2014-10-19 20:51:51