[英]rails belongs_to has_many please explain
我有以下內容:
帶有列的User
模型:
id user_id password created_at updated_at
用列Store
模型:
id store_id store_name create_ad updated_at
基本上,一個用戶可以屬於多個商店。 因此,我想獲得一個查詢,例如“獲取用戶所屬的所有商店”
我建立的關系是:
class User < ActiveRecord::Base
belongs_to :store, :foreign_key => "store_id"
end
class Store < ActiveRecord::Base
has_many :user, :foreign_key => "store_id"
end
這些正確嗎?
最終,我想確定用戶標識,密碼和商店標識是否應該能夠登錄。
那么如何在此上使用find_byXXX
? 因此,如果返回帶有傳遞的用戶ID,密碼和storeId的行,我將知道用戶是否應該能夠登錄?
我注意到以前曾問過belongs_to和has_many問題,但從這些問題中我並不能很好地理解。 也許特定於我的問題的答案會有所幫助...
因此,您已經說過用戶屬於許多商店。 一個商店屬於多少個用戶? 如果答案大於1,那么您需要的是has_and_belongs_to_many
和第三個數據庫表。 該表實質上將包含( store_id
, user_id
)對。
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
盡管Rails並不需要,但是建議您為此關系創建一個模型,並使該關系在該模型上雙向。 稍后您將感謝您。
class User < ActiveRecord::Base
has_many :userstores
has_many :stores, :through => :userstores
end
class Store < ActiveRecord::Base
has_many :userstores
has_many :users, :through => :userstores
end
class UserStore < ActiveRecord::Base
belongs_to :user
belongs_to :store
end
您正在尋找has_and_belongs_to_many關系。 您的表和模型應如下所示:
用戶表:
id password created_at updated_at
商店表:
id store_name created_at updated_at
聯接表(稱為stores_users):
store_id user_id
在您的模型中:
class User < ActiveRecord::Base
has_and_belongs_to_many :stores
end
class Store < ActiveRecord::Base
has_and_belongs_to_many :users
end
要獲得用戶的商店:
User.stores
有關更多信息,請參見rails API 。
似乎您對ActiveRecords在基本級別上的工作方式做出了許多錯誤的假設,因此,我建議您閱讀正式且非常簡單的ActiveRecord Associations指南 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.