• rails常用小技巧合集(一)



    1:helper_method :current_user
    这样可以在页面上调用current_user方
    2:include UserHelper
    这样可以在controller中调用helper内的方法
    3:model中使用路由方法
    a> Rails.application.routes.url_helpers.urlhelper方法名
    b>include Rails.application.routes.url_helpers

    源码位置: actionpack/lib/action_dispatch/routing/url_for.rb
    使用示例:
    class User < ActiveRecord::Base
      include Rails.application.routes.url_helpers
             
      def base_uri
         user_path(self)
      end
    end
    User.find(1).base_uri # => "/users/1"   
    #或者直接使用
    Rails.application.routes.url_helpers.user_path(self)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4:after_save和after_commit
    after_save是在数据库中添加数据完成后执行的
    after_commit 是rails把每次和数据库交互当成一个事务,
    begin … save… commit 之后执行

            after_commit  do |good|
              puts good.name
            end
            after_save do |good|
              puts good.name + "三三三四四"
            end
     测试代码:Good.build_for_demo({}).save
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
        输出:
         BEGIN
          SQL (0.5ms)  INSERT INTO `goods`
           (`name`, `spec`, `ref_price`, `points`, `par`, `created_at`, `updated_at`) 
           VALUES 
           ('示例奖品', '250ml', 6.0, 120, 100, '2018-02-05 09:33:31', '2018-02-05 09:33:31')
            示例奖品三三三四四
           (2.1ms)  COMMIT
        示例奖品
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    5:routes中 namespace 和 scope区别
    使用 namespace 创建嵌套路由,自动创建命名空间前缀,通常用于管理一组相关的路由,并且通常会影响路由名称和控制器查找。

    使用 scope 创建路由作用域,可以设置一些路由选项,但不会自动创建命名空间前缀,通常用于分组和管理路由,而不需要引入额外的命名空间前缀。

    namespace 用于创建一个嵌套的路由命名空间
    它会自动创建一个带有命名空间前缀的路由

    namespace :admin do
    	resources :products
    	resources :orders
    end
    创建类似/admin/products、/admin/orders等路由
    
    • 1
    • 2
    • 3
    • 4
    • 5

    scope 用于创建一个路由作用域,但不会自动创建命名空间前缀

    scope :admin do
      resources :products
      resources :orders
    end
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    6: 在特定条件下对模型的字段进行验证

        with_options unless: :pending? do
          validates :name, presence: true
          validates :code, presence: true
          validates :code, uniqueness: true
        end
    
        # 帐号rejected状态,需要验证rejected_desc
        validates :rejected_desc, presence: true, if: :rejected?
    
        # 帐号enabled expired状态,需要验证expires_at
        validates :expires_at, presence: true, if: "enabled? || state.expired?"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    7: accepts_nested_attributes_for
    允许父模型接受来自关联子模型的属性,并在父模型的表单中创建或更新关联子模型的记录

    class Author < ApplicationRecord
     has_many :books
     accepts_nested_attributes_for :books
    end
    
    class AuthorsController < ApplicationController
     def create
       @author = Author.new(author_params)
       if @author.save
         # 处理成功保存的逻辑
       else
         # 处理验证失败的逻辑
       end
     end
    
     private
    
     def author_params
       params.require(:author).permit(:name, books_attributes: [:title, :publication_date])
     end
    end
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    8: How Rails Finds Your Templates
    Admin::GoodsController.new.send(:_prefixes) => [“admin/goods”, “admin/base”, “application”]

    用于获取 Admin::GoodsController 控制器的视图模板路径前缀(prefixes)。这个前缀用于告诉Rails在哪里查找与控制器相关的视图模板文件。

    在这个例子中,_prefixes 方法返回了一个数组 [“admin/goods”, “admin/base”, “application”],这意味着Rails将按照以下顺序查找视图模板文件:

    1. 先在 app/views/admin/goods 目录下查找模板文件。
      如果没有找到
    2. 继续在 app/views/admin/base 目录下查找。
    3. 在 app/views/application 目录下查找
    4. 这是一个通用的视图目录,适用于整个应用程序

    9: 为什么子类都要实现self.model_name
    @good 页面上使用的是统一的[:admin,@good],这样@good的model_name 才会访问路由/admin/goods/ceate

    10: simple_form 下拉框内容定制显示
    label_method:

    <%= f.input :par, label: "话费额", collection: [1,10,20,30,50,100], label_method: ->(n){ "#{n} 元"}, include_blank: false, hint: "话费为全国全网通用" %> 
    
    • 1

    11:views路径下是否存在某个文件

     lookup_context.exists?(@good.type_name, "admin/goods/form", true) 
    
    • 1

    12: :require_new => true

    在 Rails 中,子事务的 rollback 是否被父事务知晓可以通过使用 :requires_new => true 选项来控制。这个选项通常用于确保子事务的 rollback 能够传播到父事务中,从而影响父事务的执行。

    13: 重定向路由并且传递常数

    resources :approvals do
      collection do 
        get :approved, to: "approvals#index", defaults: { filter: { state: :approved }} 
      get :submitted, to: "approvals#index",  defaults: { filter: { state: :submitted }} 
      end 
    end
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    测吧(北京)科技有限公司项目总监王雪冬一行访问计算机学院探讨合作
    SPC 统计过程控制
    单节点服务架构
    Shell:正则表达式
    【数据结构】时间复杂度与空间复杂度
    Hadoop运维工具箱之HDFS集群扩容与缩容-尚硅谷大数据培训
    13.cuBLAS开发指南中文版--cuBLAS中的Level-1函数copy()和dot()
    C++日期和时间编程小结
    [Linux]文件路径名称含有‘/‘以及‘.‘的书写规则
    python中的属性管理机制
  • 原文地址:https://blog.csdn.net/noob_cherry/article/details/133685699