美文网首页
Rails 里面的 merge

Rails 里面的 merge

作者: 我天真无邪 | 来源:发表于2017-05-26 15:06 被阅读126次

__ 所有的代码直接手撸、没有验证过 直接在 MarkDown 里写的 QAQ __

有一些编码风格 & APi设计的时候嵌套风格 & APi错误处理风格夹杂在其中

待完善

背景模型

# 团队 - 拥有团队的项目 & 团队的成员
# 用户 - 有可以访问的多个项目
# 项目 - 归属于某个团队 & 项目有很多的成员
# 访问 - 用来记录用户 & 项目之间的权限

class Team < ApplicationRecord
  has_many :users
  has_many :projects
end

class User < ApplicationRecord
  has_many   :teams
  has_many   :accesses
  has_many   :projects, through: :accesses               # 这里就是用户能访问的项目
end

class Profile < ApplicationRecord
  self.table_name = "user_profile"
  has_one :user
end

class Access < ApplicationRecord
  belongs_to :project
  belongs_to :user
end

class Project < ApplicationRecord
  belongs_to :team
  has_many   :accesses
  has_many   :members, through: :accesses, source: 'user' # 项目有很多成员
end

合并复杂查询

  • 需求: 查询 当前用户 在 当前团队 的 所有有权限访问 的项目

class BaseController < ApplicationController
  before_action : current_user
  
  def current_user
    @current_user ||= User.first
  end
end

module Teams
  class BaseController < ::BaseController
    before_action :current_team
     
    def current_team
      @current_team ||= User.first
    end
  end
end

module Teams
  class ProjectsController < BaseController
    def index
      @projects = @current_team.projects.merge(@current_user.projects)
    end
  end
end
  • 需求: 根据 Profile 里面记录的生日 对用户进行排序
class UsersController < BaseController 
  def index
    #where 属于乱入 & 这里是一些比较常见的写法
    #@users = User.joins(:profile).where("user_profile.address LIKE ?", 'HANG').order("user_profile.birth_day")
    users = load_users
  end
  
  private
  def load_users
    users = User.includes(:profile).joins(:profile).merge(Profile.order(:birth_day))
    raise ErrorOnUsersControllerIndexMethod unless users
    return users
  end

end

相关文章

  • Rails 里面的 merge

    __ 所有的代码直接手撸、没有验证过 直接在 MarkDown 里写的 QAQ __ 有一些编码风格 & APi设...

  • 巨坑的Linux部署

    部署遇到的坑: 1.专案没有Merge 首先,我在项目rails_recipe终端那里,想要部署进去,发现错误了,...

  • git merge一个指定文件

    git里面的merge是全merge ,没有单个文件merge。 要实现一个文件的merge ,可以使用git c...

  • Rails里面的includes

    Rails里面includes是比较常用的 依旧先码出背景 关联 includes方法指定使用关联时要按需加载的间...

  • rails 路由学习1

    rails config/routes.rb 指定路由的代码如下 上面的代码定义了5种风格的路由,rails在启动...

  • heroku配置rails程序

    省略部分 rails程序和heroku安装省略 预备工作 rails里config/environments/pr...

  • gem安装Rails失败

    使用gem install rails出现下面的信息: Building native extensions. ...

  • rails5.1 webpacker尝试

    rails5.1, 主题是Loving Javascript,并且在rails的项目里融入了webpack, ya...

  • ruby-Time/Date1

    鉴于前几天没提到的rails中的时间/日期常用方法,补充下面的方法。rails中常用的取时间节点的方法,对于计算天...

  • 无法再 RubyMine 正常使用 Rails 命令

    升级了最新版的 RubyMine 突然发现,不能在Terminal里正常使用Rails的命令了,提示:Rails ...

网友评论

      本文标题:Rails 里面的 merge

      本文链接:https://www.haomeiwen.com/subject/uqkxfxtx.html