0

Rails アプリのバージョニングの実装 モデルのすべてのバージョンを表示するビューに、元に戻すなどの追加機能が必要paper_trailです。バージョニングには gem を使用します。

すべてのモデルのようなコントローラー関数versionsとビューを作成することでそれを実行できることはわかっていますが、すべてのモデルに対して一度に実行したいと考えています。model.versions属性は常に同じように構造化されているため、これは可能なはずです。

理想的には、URL は次のようになります/pages/testpage/versionstestpage、 はページ ID です。

これは、レールのネストされたルートの概念に似ているようです。

resources :pages do                                                    
    resources :versions                                                  
end

ただし、ネストされたルートの問題は次のとおりです。

  • モデルごとに追加の構成が必要
  • testpageインスタンスであるモデルを知らずにオブジェクトにアクセスすることはできません。また、バージョン コントローラーに提供されるのは params ハッシュだけであるため、モデルを特定する方法を見つけることもできませんでした。

私は、最初のアイデアに従わない可能性のある代替ソリューションに対して完全にオープンです。

4

2 に答える 2

1

あなたにそれを書いてApplicationController、helper_methodとして定義してください。

例えば

class ApplicationController < ActionController::Base
  helper_method :current_time

  def current_time
    Time.now
  end
end

これcurrent_timeで、コントローラーまたはビューのどこでも計算できます。

また、個別のモジュール/クラスを記述して、そこにヘルパーメソッドを定義することもできます。ApplicationControllerこのファイルを自分にも含める必要があります

テーマ変更後のUPD

私はあなたの実際の質問について考えていませんでした。しかし、私はあなたのアプローチがここで最高だと言うことができます。

テストが難しい新しい機能を作成するのではなく、新しいリソースを作成する必要があります。したがって、新しいリソース(コントローラー):バージョンを作成し、このコントローラーを試してみてください。

たとえば、どのように機能するか:

/versions/pages/132
/versions/comments/1003

それを実現する方法:

match "/versions/:model/:id", :to => "versions#index"

コントローラ内:

class VersionsController < ActionController::Base
  def index
    @object = my_type.find(params[:id])
    @versions = @object.versions
  end

  private
  def my_type
    params[:model].constantize
  end
end

もちろん、ルートを好きなように変更できます。

match "/:model/:id/versions", :to => "versions#show"

これ/pages/testpage/versionsで、新しい奇妙なロジックがなくても、かなりうまく機能するようになります。

UPD 2

あなたがこのルートを持っていると想像してください:

match "/:model/:id/versions", :to => "versions#index", :as => :versions

そして、このオブジェクト:

@page = Page.last
@hotel = Hotel.find(123)
@comment = @page.comments.first

バージョンのリンクをどのように作成しますか?

<%= link_to "Versions of this page", versions_path(:model => @page.class.to_s, :id => @page.id) %>
<%= link_to "Versions of this hotel", versions_path(:model => @hotel.class.to_s, :id => @hotel.id) %>
<%= link_to "Versions of this comment", versions_path(:model => @comment.class.to_s, :id => @comment.id) %>
于 2011-04-20T13:47:01.840 に答える
0

I would suggest passing a param such as 'type' and stuff the model name there. Then in your controller you can do:

class VersionsController < ApplicationController
  def index
    model = params[:type].classify.constantize
    @obj = model.find(params[:id])
  end
end

For your links, you can pass queries to the link_to helper

<%= link_to versions_path(@model, :type => @model.class) %>

Or something along those lines.

于 2011-04-20T15:02:17.193 に答える