簡體   English   中英

Ruby on Rails模型混亂

[英]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_userTestUser模型的實例。 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.

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