#118 Ruby on Rails - Tips and Tricks


In this episode, we will go through some of the tips and tricks that we often take for granted. We will be looking at nested routes, scopes, migrations and more.
rails tips tricks 14:53


Terminalrails g scaffold brand name
rails g scaffold product brand:references name 'price:decimal{5,2}'
rails db:migrate
rails db:seed
rails routes
Gemfilegem 'faker'
db/seeds.rb10.times do
  Brand.create do |brand|
    brand.name = Faker::Company.name
    100.times do
      brand.products.new do |product|
        product.name = Faker::Commerce.product_name
        product.price = Faker::Commerce.price
models/brand.rbclass Brand < ApplicationRecord
  has_many :products, dependent: :destroy
models/product.rbclass Product < ApplicationRecord
  belongs_to :brand #, optional: true

  scope :cheap_products, -> { where(price: 0..50.00).order(price: :asc) }
  # scope :expensive_products, -> { where(price: 50.01..Float::INFINITY).order(price: :asc) }
  scope :expensive_products, -> { where(price: 50.01..1.0/0.0).order(price: :asc) }
  # def self.cheap_products
  #   where(price: 0..50.00).order(price: :asc)
  # end
config/routes.rbRails.application.routes.draw do
  resources :brands do
    resources :products
products_controller.rbclass ProductsController < ApplicationController
  before_action :set_brand, except: [:index]
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  def index
    @brand = Brand.includes(:products).find(params[:brand_id])
    @products = @brand.products

  def show

  def new
    @product = @brand.products.new

  def edit

  def create
    @product = @brand.products.new(product_params)

    if @product.save
      # redirect_to brand_product_path(@brand, @product), notice: 'Product was successfully created.'
      redirect_to [@brand, @product], notice: 'Product was successfully created.'
      render :new

  def update
    if @product.update(product_params)
      redirect_to [@brand, @product], notice: 'Product was successfully updated.'
      render :edit

  def destroy
    # redirect_to brand_products_path(@brand), notice: 'Product was successfully destroyed.'
    redirect_to [@brand, :products], notice: 'Product was successfully destroyed.'

    def set_brand
      @brand = Brand.find(params[:brand_id])
    def set_product
      @product = @brand.products.find(params[:id])

    def product_params
      params.require(:product).permit(:brand_id, :name, :price)
products/_form.html.erb<%= form_with(model: [@brand, product], local: true) do |form| %>
  <td><%= product.name %></td>
  <td><%= product.price %></td>
  <td><%= link_to 'Show', [@brand, product] %></td>
    <%# link_to 'Edit', edit_brand_product_path(@brand, product) %>
    <%= link_to 'Edit', [:edit, @brand, product] %>
  <td><%= link_to 'Destroy', [@brand, product], method: :delete, data: { confirm: 'Are you sure?' } %></td>

Nickiam said 10 months ago:

Nice episode! I really like the Tips and Tricks theme, would love to see more like this!

Agung Setiawan said 10 months ago:

Agung Setiawan said 10 months ago:

Login to Comment
they're handing now yeah and that and that and learned lessons and for the kids and tips and tricks with and wales applications so in this example were to be working off of a fresh rails five one for application and so the person employed to do is generate some scaffold and for scaffold out grade is the brand in all have a name then the second scaffold out created as a products and so within our product or didn't have a brand that were using this preferences and this will create a brand owners or id attribute they're also create a heat index on this brand id and then i would create a prius with the decimal and i can put the precision in scale in here by wrapping the whole attribute in quotes ending is a mustache is set in the kitchens it so go ahead and run rail steve be migrate to my grave the database and so if we look at our scheme of we see our products with the image or brand id no we also see the index friend i'd be in them with the price we ever percent and five with the scale of two it's for the next thing i want to do is to generate some fake gave it to work with so we didn't have some things out and to do this on an easy faker gem genre but our research wells application the new within the season and create a fake products then i'm also going to create some fake brands so well first grade the brand study ten times do the soldiers cradle of reckoning create the brands so-called brenda create and has a block here by passing in a block going to be able to interact with this new brand then once the block is close it should say that a call the brand out named equals to the nikes if they could jump to create a brand name some call fake or an hour easy company module and i dislike name there would also create some products so called hundred times to their within here we can call brand god products that create do product in the product as have a couple attributes the brain dead you will automatically be set by a call in the brain dot products to the nozzle had the product name in the midst of the product a tv faker commerce and then the product name i can also set the product price so call the product they're pricey calls to the faker commerce and then price if we look at the product we can see that a party has he belongs to pray and that's because we we created the scaffold we had the brand references alive or within the brand you also have to come in here to say has many products and if we do we do brand we would also want to delete the associated products so we called the pendant and then destroyed and so back in our console we can run rails the pc this will create all the products and brands whether you can see that we get in there and this is you cannot call the creator unless the parent to say the seller saints this is referencing from our brand products created and instead of calling create here we call knew then they should work that's because the parent has to be first created saturday create it'll be a little block so that their terminal we won this again it is see that it is now successfully created our products as walls are breaths so this is a big guy to that many people wall we usually going into within their rouse outta kitchen somewhere and this is pretty easy easy example the teensy so within that create the our association is you would more to call the bread products created because again it's going to throw that air and if you do want to override their behavior where you are able to call create within the block or within the request that's also creating the parent record then within the product where it belongs to the brand we can call the optional true and this would allow us to do that if there are some valid use cases for this one for typically started to look for it to the ball conventions unless we actually have a good he skates and so on the brand show page or two without all of the products and so i just copy the table from our products scaffold and and i just wondered the brand products and because i have this brand products this is going to return a active record collection with this question we're going to lose during winter each one of these products they were able to do this because under the products folder we have a underscore product partial the product partial is just a rope with the different calls this way more information and so running our application we can see are kinda from friends that we do your do the show page or one of these that we can see all of the products are associated to that particular brand so now let's say if we wanna find on the cheap products that are under fifty dollars until within our products model we did creating new class match it with self like cheap products within europe we can say where they we went to search on the prize that we want to find all the prices that are cheap no friends you do fifty dollars that was going sort of price party is sending so being from cheapest to most expensive they don't something like this works however if i'm able to get away with two and a bomb order now would prefer to do that as well so instead we can create a skill that will call the scope the cheap products calmer and it will create l m de heer know we would just pass and our query the name we are renewing our products in the weekend chain in on the products the cheap products and so now we visit our brains another console put up on the left side also one of the brain stew see the products and you can see the resulting query this of this query executed pretty quickly and on the right hand side you see all of the different products that are under fifty dollars facilitate we also want to get expensive products all just cornell has fallen and now does change is too expensive even changer search for the price was safely would return anything that is great and fifty dollars so he does something like this that we need a high end we could just put in a magical number here that's no price is ever going to exceed this where there's a much better way to do it she could call the concept the float infinity this will then do anything that is greater than fifty dollars a pop tune kennedy if we refresh our application you see that we're checking for the prices is greater than than it is looking at the price and only the fifty diet zero one this past them so this is going to return a theme that is greater than fifty dollars and as for the affinity can also be written as it was something like one point zero divided by zero point zero the typically interactive he tried to divide by zero didn't get an error in the same thing it would be if you were to divide one by zero will ever win the coliseum o'dowd syrup it's actually going to return infinity so if we want to run the console weekend basis and to see when it returns and you can see that those returns infinity in every call the flow of infinity you see better returns is something that we can check to see if these were evil to each other and they are next let's look at why they would take to the floor resources of products under the brands self we remove the line for resources and then on the brands create a block and within a block we had our resources products then close out the block water is to change the results and also the your eyes better use when working with products they're within our terminal we tried rails ralph's we can see the routes and first we see our brains and the brands are just the normal way that they work however now our products are names based on with the brands and they rely on having a brand id and that we have the products then the idea of the product so for each one of the actions with their products we do have to require this brand id and so within the products control or action we could create a notable for action that one up with this about setting the product so protocol this the separate and so in the private method of discontent copy the cell they will change the name from said product is separate and we consider brain he will do the brand and this i work in a funded by the brand id it's an owl once we have a friend said and they cant remember that we put our bill for action of separate and before the before action the same product so this will execute first we get a center product we don't need to search from the products but instead we can set this from the brand and we get a cold products that's fine and deep friends i'd be and for some food fight the index section you may want to put a includes products within your lover on what necessarily do that for all would go because we are just searching for one product most cases however when you're listing them out he gets all that plus one queried but it was something like includes a dandy products where brenda skates and i do need to optimize as ben howland extract the cell they don't put it up at the top but as for the next action there within the ball for actions that bread or do something like a accept then the index and i had multiple want to be said could cover this over and to raise while so now let's look at each one these actions so the next action we won called project on all because we're wanting all the products for any particular brand so we get a call the ad brenda products with the new action we would do the same thing we're we're calling the app brand their products news same thing for the creative action but then we get into something a little bit more tricky because we paid directly just redirect to the product because it is well liked on the brand stuff we go back and look at our routes with the products so we're action you would have to call something like brand product we have to pass in the granddaddy and the product id so one way to do that is to call the brand product path and this will take us tv show action of the ad brand in the ad product this will work all over at all like this method because even though it is pretty direct until then it's a lot of extra typing and there's actually a better way or the way that i prefer to have more knowledge is common to sell and is set up putting in the full path we just have regret too the ad bread and that product of free passes and as a raid and it's going to do the exact same thing as kong the brand products packed with the bread and the product and so with or update actions we do the exact same thing where we're really directing we're putting in the air raid friend a product they want to destroy that shit we're wanting to get to the index and this is a bit trickier because we don't really have the ad product as referencing one single product we don't have the array of products so if we go back and look at our routes for the next section of our brand products we had the brand products path so you could do this bread products path it has in the brand and this will take you to all of the products of the brand what are big and i don't really like to win this because i think that there's a better way to do it that said i just have their raid brand then also that's invisible products in this would take us to be an exception of our products under a particular brand and overall i'd do prefer this way of editing my routes what it is see this once we get into the views why is just a bit cleaner in west type thing and so within our products partial under the products directory we have our product and this is going to throw an error so just like was all before we would call the ad brand today we would call our product in a week into something a bit trickier with the added on a path and so with the end up on a path to get this to work correctly will that t v and a brand products have and it will it had to pass in the bread and the product so can i really don't like doing this because i think that there is a much better way to do it some guy again just do some code folding here then i'll comment the top or no it's an owl one of follow the same city that then before with passing in the air ray leonard this is good to do the show action instead of the ad in action set of facts as we ever had that brand products is the easiest way to remember the past as with the attic first and then the brand and then the product so op with the added sample here first and then we have added french product that matches where bathroom we as an let's give this a shot and finally with our link to destroy we do need a pass and enter rate with their brand then the product and so i'm wrong again i think that this is much cleaner and a lot less hyping him having the full path they explicitly said movies out it's about going into ours was a brand's we can show one of these then it shows all of our products that were not getting any errors with the links not being scrapped or the bottom you can see that this is taken us to the brands one products fifty four he added that should also works with the bread sworn products fifty four with the four slash at it in their within the forum for products we would also add to fit see form with any worse referencing the model would just do the exact same thing where we pass the brand and then the product as a rake in this also works with things like forecasts a course of school for and so go back to our brains making go into one of these in that we can hit the show action on one of the products that we can see the data there but we're back we didn't get to keep it in action and this works is well what do we change a prize our prices change and then we can also destroy them and it takes us right back to our list of products still under the brand wow that's all for this episode thank you for watching