DEV Community

Mary Webby
Mary Webby

Posted on

Refactoring MSM GUI 2

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
Enter fullscreen mode Exit fullscreen mode

meta methods

belongs_to

belongs_to( :name_that_we_want, :class_name => "", :foreign_key => "" )
Enter fullscreen mode Exit fullscreen mode

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"  )
Enter fullscreen mode Exit fullscreen mode

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" )

Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

has_many

has_many( :name_that_we_want, :class_name => "", :foreign_key => "" )
Enter fullscreen mode Exit fullscreen mode

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 )
Enter fullscreen mode Exit fullscreen mode

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)