cluster1
cluster1

Reputation: 5694

Rails Models: Where does this object come from?

Following code:

class Product < ApplicationRecord
    validates :name, presence: true
    validates :price, numericality: { 
        greater_than_or_equal_to: 0.0 
    }
    validates :description, presence: true
 
    belongs_to :user
 
    def owned_by? owner
        user == owner # Where does the user-obj. come from?
    end
end    

It works. What I don't get is: Where does the "user"-object come from? Please see the line with comment!

"user" is nowhere declared / assigned a value.

Does someone know how that works and can it explain to me?

Upvotes: 2

Views: 29

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33450

From the ActiveRecord::Associations::ClassMethods#belongs_to API docs:

Methods will be added for retrieval and query for a single associated object, for which this object holds an id:

association is a placeholder for the symbol passed as the name argument, so belongs_to :author would add among others author.nil?.

Example

A Post class declares belongs_to :author, which will add:

Post#author (similar to Author.find(author_id))
...

So in your case, after declaring the belongs_to :user relationship you get that bunch of methods, among them user.

Upvotes: 4

Related Questions