[英]Ruby on Rails model Confusion
我遇到了下面的代碼,這超出了我的輕描淡寫。 我正在努力從頭三天開始完全掌握它,但是沒有。
class TestUser < ActiveRecord::Base
self.table_name = 'garden'
belongs_to :account
accepts_nested_attributes_for :garden
上面的整個代碼對我來說是無法理解的。
class TestUser < ActiveRecord::Base
self.table_name = 'garden'
authenticates_with_sorcery!
belongs_to :account
accepts_nested_attributes_for :garden
逐行細分:
class TestUser < ActiveRecord::Base
這是定義一個稱為TestUser
的類,該類從ActiveRecord::Base
繼承。 連接到活動記錄(即具有數據庫表)的導軌中的所有模型均具有相同的簽名。 從ActiveRecord::Base
繼承為TestUser
模型提供了一些神奇的功能。 在http://guides.rubyonrails.org/active_record_basics.html上了解更多有關它的信息。
self.table_name = 'garden'
這行說TestUser
模型應該連接的表是garden
。 默認情況下, TestUser
模型鏈接到test_users
表。 這條線正在改變這種行為。
實際上,應該是gardens
因為所有表名都應為復數形式; gardens
表用於存儲有關許多花園對象的信息。
在http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/table_name中了解table_name
authenticates_with_sorcery!
這行代碼說系統使用魔法寶石進行身份驗證。 在http://railscasts.com/episodes/283-authentication-with-sorcery了解更多
belongs_to :account
這行內容是說TestUser
對象與Account
模型有一個belongs_to
關系。 有了這種關系,您可以使用test_user.account
方法找到一個test_user's
帳戶。 假設test_user
是TestUser
模型的實例。 即test_user = TestUser.new
。 在http://guides.rubyonrails.org/association_basics.html#the-belongs-to-association上了解有關belongs_to
協會的更多信息
accepts_nested_attributes_for :garden
此行說,當您保存TestUser
對象時,可以在Garden
對象上保存屬性。 在http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html上了解有關accepts_nested_attributes_for
更多信息。
最后,一條建議可以幫助您更好地理解Rails世界中的所有內容:仔細閱讀Rails教程,全面了解Rails概念。 強烈建議您在https://www.railstutorial.org/book上免費獲得Rails教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.