ruby dhh Rails资源示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby dhh Rails资源示例相关的知识,希望对你有一定的参考价值。

# config/routes.rb
resources :documents do
  scope module: 'documents' do
    resources :versions do
      post :restore, on: :member
    end

    resource :lock
  end
end


# app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
  include ProjectScoped

  def index
    @documents = @project.documents
  end

  def show
    @document = @project.documents.find(params[:id])
  end

  def new
    @document = Document.new
  end

  def create
    @document = @project.documents.create! document_params.merge(creator: current_person)
  end
end


# app/controllers/documents/locks_controller.rb
module Documents
  class LocksController < ApplicationController
    include DocumentScoped, ProjectScoped

    def update
      @document.lock!(current_person)
    end

    def destroy
      @document.unlock!(current_person)
    end
  end
end


# app/controllers/documents/versions_controller.rb
module Documents
  class VersionsController < ApplicationController
    include DocumentScoped, ProjectScoped

    before_action :set_version

    def show
    end

    def restore
      @document.restore!(@version)
    end


    private
      def set_version
        @version = @document.versions.find(params[:id])
      end
  end
end


# app/controllers/concerns/document_scoped.rb
module DocumentScoped
  extend ActiveSupport::Concern
  
  included do
    before_action :set_document
  end
  
  private
    def set_document
      @document = @project.documents.find(params[:document_id])
    end
end

以上是关于ruby dhh Rails资源示例的主要内容,如果未能解决你的问题,请参考以下文章

Ruby on Rails SOA 设计资源和示例

ruby-on-rails - 嵌套资源问题

Ruby on Rails Cron 作业示例

ruby Rails Controller代码示例

Ruby on Rails 路由解析

Ruby on Rails 在现有资源上返回 404