Creating a standard instance method
- Standard practice for getting a specific piece of information from each database
class Character < ApplicationRecord
def movie
key = self.movie_id
matching_set = Movie.where({ :id => key })
the_one = matching_set.at(0)
return the_one
end
end
meta methods
belongs_to
belongs_to( :name_that_we_want, :class_name => "", :foreign_key => "" )
so for example, if you wanted to change the code above, you would turn the prompt given above into this
belongs_to( :movie, :class_name => "Movie", :foreign_key => "movie_id" )
since you are typically name all of these the same convention, you can even go further and take out the classname.
belongs_to(:movie, :foreign_key => "movie_id" )
they decided to write this method if you omit the class name, they're going to guess that the class name matches the method name that you select, which is the case 99% of the time.
belongs_to(:movie)
has_many
has_many( :name_that_we_want, :class_name => "", :foreign_key => "" )
producing a lot from this specific method so we want to use it for when we would we would be getting information back that comes in many, say characters, or comments, or movies. stuff like that.
belongs_to( :name_that_we_want )
can also deduce it the same way like before if the class name matches the method name, then rails will assume that that is the name that you are going to use unless stated otherwise.
example on how to use in rails console
type these into rials console to understand where we can add on methods to meta methods.
Character.joins(:movie).where("movies.year > 1994")
Top comments (0)