Reputation: 15
I came across the following code which is beyond my understating. I'm working hard to grasp it completely from previous 3 days but couldn't.
class TestUser < ActiveRecord::Base
self.table_name = 'garden'
belongs_to :account
accepts_nested_attributes_for :garden
The entire above code is not understandable for me.
Upvotes: 0
Views: 38
Reputation: 13067
class TestUser < ActiveRecord::Base
self.table_name = 'garden'
authenticates_with_sorcery!
belongs_to :account
accepts_nested_attributes_for :garden
Breaking it down line by line:
class TestUser < ActiveRecord::Base
This is defining a class called TestUser
which is inherited from ActiveRecord::Base
. All models in rails connected to active record (i.e. having a database table) have the same signature. Inheriting from ActiveRecord::Base
provide TestUser
model with some magical abilities. Read more about it at http://guides.rubyonrails.org/active_record_basics.html
self.table_name = 'garden'
This line is saying that the table that TestUser
model should connect to is garden
. By default TestUser
model is linked to test_users
table.
This line is changing that behavior.
Actually, it should be gardens
as all table names should be plural; gardens
table is for storing information about many garden objects.
Read about table_name
at http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/table_name
authenticates_with_sorcery!
This line says the system uses sorcery gem for authentication. Learn more about it at http://railscasts.com/episodes/283-authentication-with-sorcery
belongs_to :account
This line is saying that the TestUser
object has a belongs_to
relationship with Account
model. With this relationship in place, you can find a test_user's
account with the test_user.account
method. This is assuming test_user
is an instance of TestUser
model. i.e. test_user = TestUser.new
. Read more about belongs_to
association at http://guides.rubyonrails.org/association_basics.html#the-belongs-to-association
accepts_nested_attributes_for :garden
This line says that you can save attributes on Garden
object when you are saving a TestUser
object. Read more about accepts_nested_attributes_for
at http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Finally a piece of advice to help you understand everything better in rails world: Go through a thorough rails tutorial to get a good understanding of rails concepts. The freely available Rails Tutorial book at https://www.railstutorial.org/book is highly recommended.
Upvotes: 1