Ruby: Scaffold Generator, AREL, Validation, One-to-many, Many-to-many

14 篇文章 0 订阅

Scaffold Generator

It generates:

  • Model/migration
  • contoller file and implementation
  • the entire view folder
  • all restful routes
rails new blogDemonstration

cd blogDemonstration/

rails g scaffold Post title:string content:text

rails d scaffold Post
# in routes.rb add the root route

root "posts#index"

Arel

# show query result using gem
rails c

Hirb.enable

Post.all

Post.all.where(title: "test").where(content: "ruby")

Post.all.where("id > 2")				# where returns all, return [] when not found

Post.all.find_by(title: "test")	# find_by returns the first, return nil when not found

Post.all.find(1)								# throw ERROR if not found

Post.all.limit(3)								# give the first 3 existing

Post.all.where(title: "test").order(:created_at)

Validation

  1. define a method in the model file
    1. check if your desire validation passes
    2. if not, add the column name as a symbol and the error message to the errors object
  2. pass the method as a symbol to validate
class User < ActiveRecord::Base
  validate :penn_email
  
  def penn_email
    unless email.include? 'upenn.edu'
      errors.add(:email, 'is not a penn email')
    end
  end
end

https://guides.rubyonrails.org/active_record_validations.html#custom-validators

One-to-many

rails g scaffold User name:string

rails g scaffold Post title:string content:text user:references

rails db:migrate
# Post.rb model file
belongs_to :user

# User.rb model file
has_many :posts, dependent: :destroy

Many-to-many

Create a third table to seperate a many-to-many to two one-to-many

rails g scaffold Course name:string
rails g scaffold Student name:string

rails g Model Registration Course:references Student:references
# in Registration.rb model file
belongs_to :student
belongs_to :course
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值