0

今考えていることは…

私は本(エントリ)でいっぱいの図書館を持っています。各本には多くのチェックアウト (埋め込みドキュメント) があります。

私がやりたいと思うのは、チェックアウト時に、埋め込みドキュメントとして新しい「チェックアウト」を作成することです。チェックイン時に、チェックアウトを編集して「date_checked_out」フィールドを追加したい...

問題は、現在のモデル/コントローラーがチェックインまたはチェックアウトのたびに新しいエントリを作成することです...したがって、二重に冗長です...

これについて最善の方法は何ですか?詳細が必要ですか?

チェックアウト コントローラー:

  def new
    @entry = Entry.find(params[:entry_id])
    @checkout = @entry.checkout.new
    respond_to do |format|
      format.html {render :layout => false}
    end
  end

  def create
    @entry = Entry.find(params[:entry_id])
    @entry.update_attributes(:checked_out => "Out")
    @checkout = @entry.checkout.create!(params[:checkout])
    redirect_to "/", :notice => "Book Checked Out!"
  end

class Checkout
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes

  field :checkout_date, :type => Time
  field :checkout_date_due, :type => Time
  field :book_in, :type => Time, :default => Time.now
  field :book_out, :type => Time, :default => Time.now

  embedded_in :entries, :inverse_of => :entries
end
4

2 に答える 2

0

純粋な REST のままにして、更新アクションを Checkout コントローラーに追加します。

また、あなたのエントリーモデルを投稿してください。あなたのコードから、エントリには has_one チェックアウトがあり、チェックアウトはエントリに属していると想定しています。

何かのようなもの:

* OPが条件をチェックしながらこれがどのように機能するかを見たいと思われるので編集

  ... original boilerplate code ommitted 
  def update
    @entry = Entry.find(params[:entry_id])
    # if the book is checked out
    if @entry.checked_out == "out"
      # then update it 
      @entry.update_attributes(:checked_out => "whatever" # though I'd seriously consider changing checked out to a boolean - if it's either out or in, true or false makes sense. Ignore this advice if there are more than two states
      @checkout = @entry.checkout
      respond_to do |format|
        if @checkout.update_attributes(:checked_out => "newValue")
        ...
        else
        .. handle errors
        end
      end
    else
      #the book does not have the correct status
      respond_to do |format|
         format.html { redirect_to some_action_path, :notice => "Entry is not out, so we cannot update its status." }
         format.json { render json: #entry.errors, status: :unprocessible_entry }
      end
    end
  end

また、コードをもう少し明示的にしたい場合は、swards のアドバイスを受けて、次のようないくつかの名前付きエンドポイントを作成することを検討してください。

def checkout

end

def checkin
end

コードを読んでいる他の誰かが、作成や更新とは対照的に、そのコントローラー アクションが何をしているのかを非常に簡単に正確に知ることができるという点で、これは理にかなっていると思います。

于 2013-05-16T02:36:31.517 に答える