rails 方法和对象

render 'new'  # 重定位到new
redirect_to @user # 跳到show页面
session[:user_id] = @user.id # session保存功能,在整个rails的生命周期都存在
session.delete(:user_id) # session删除

rails 路由(rails 通过路由配置表来转发url动作)

路由表的功能:

  • 接收识别http 请求
  • 处理url参数
  • 转发url动作

一般路由:

# 自动生成posts所有路由信息且相应除去show这个url的所有url
resources :posts, :except => :show
# 将接收到的指定格式的get请求路由(post跟id号)转发给show这个动作处理
# id是相应参数(将id这个参数保存到param中)
get 'posts/:id', :to => 'posts#show'
# 将接收到的指定格式的post请求路由(post跟id号)转发给show这个动作处理
post 'posts/:id', :to => 'posts#show'
<%= link_to '一般路由到跳转到id为1的文章',{:controller => 'posts',:action => 'show',:id => 1} %>

命名路由(比一般路由简便):不需要书写详细的信息(controlelr,action 之类的)

# 会自动生成一个名为show_posts的辅助方法
get 'posts/:id', :to => 'posts#show', :as => 'show_posts'
<%= link_to '命名路由到跳转到id为1的文章',show_post_path(1) %>

资源路由(常用路由)

# 资源路由自动生成7种访问(index, show, new, edit, create, update, destory)
# 擦~~resources 别忘最后的s
resources :posts 

添加集合路由扩展

一个:

# 1. posts_controller 中添加
def recent
end
# 2. 创建 recent.html.reb 文件
<p> 自己添加一个recent 路由 </p>
# 3. routes.rb 对资源路由进行扩展
resources :posts do
    get 'recent', :on => :collection
  end
# 以上操作之后就添加了一个命名路由且自动生成了资源路由

多个:collection do end 包裹

# 区别是生成的url格式不同
resources :posts do
    collection do
      # posts/recent     (http://localhost:3000/posts/recent)
      get 'recent'
    end
    member do
      # posts/:id/recent   (http://localhost:3000/posts/1/recent)
      get 'recent'
    end
  end

rails 数据交互

# 模型字段合法性
class User < ActiveRecord :: Base
  # validates 函数指定 在往数据库插入数据的时候要求
  # userName 不允许为空且最大长度不超过20
  validates :userName, presence: true, length: {maximun: 20}
  # 正则验证邮箱
  EMAIL = /\A[a-zA-Z0-9\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z]+\z/
  validates :email, presence: true, length: { maximum: 20 }, format: { with: EMAIL }, uniqueness: {case_sensitive:false}
end
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,317评论 19 139
  • 参考 RailsGuides中的Rails Routing from the Outside In 简介 Rail...
    零小白阅读 7,547评论 0 15
  • 当海风吹入心中 迎着太阳 看着那潮汐潮落 却一个人 在白色的屋顶上 你告诉我 这只是一次远航 海水是那么蓝 爱情却...
    一口山争阅读 520评论 2 3

友情链接更多精彩内容