0

私のアプリケーションでは、ユーザーにストアを検索してから、使用するストアを選択してもらいたいと思います。ユーザーが記事へのコメントのようにそのストアに新しい価格を追加できるフォームに移動する必要がありますが、代わりにエラーが発生します。

ActiveRecord::RecordNotFound in PricesController#new

Couldn't find Store without an ID

これらは私の協会です:

class User
  has_many :prices

class Store
  has_many :prices

class Price
  belongs_to :user
  belongs_to :store

したがって、ユーザーがストアを選択するときは、price/new使用されているストアのIDにアクセスして知る必要があります。多分次のようなものです:

<%= form_for @price, :url => create_price_store_path(@store) do |f| %>
...
<% end %>

次に、私が使用しているアクション:

class PricesController

  def select_store
    # Find the store using sunspot search
    @search = Store.search do |s|
      s.fulltext params[:search] unless params[:search].blank?
      s.paginate(:per_page => 5, :page => params[:page])
    end
    @stores = @search.results
  end

  def new
    @store = Store.find(params[:id])
    @price = Price.new
  end
end

それからこれまでの私のルート:

resources :stores do
  member do
   post :create_price
  end
end

resources :prices do
  collection do
    get :select_store
  end
end

なぜこのエラーが発生するのですか?何を修正する必要がありますか?

4

1 に答える 1

1

実際、ルートが正しく設定されていないと思います。

店舗に応じて価格を設定したい (またはその他の安らかなアクションを実行したい) 場合は、次のようにルートを設定する必要があります。

リソース :stores do resources :prices end

したがって、次のPricesControllerURL からアクセスできます。

stores/:store_id/prices/[:action/[:id]]

あなたのセットアップでは、 POST リクエストを介してトリガーできるPricesControllerという名前のメソッドがあると言っているだけです。ただし、このメソッドが定義されていません(少なくとも、提供したスニペットでは定義されていません)。create_pricestores/:store_id/create_pricePricesController

したがって、上記で書いたように、ネストされたリソースを実行している場合は、PricesController次のようにすることができます。

PricesController
  def new
    @store = Stores.find(params[:store_id])
    @price = @store.build   # this builds the Price object based on the store
  end

  def create
    # depending if your model uses `accepts_nested_attributes_for`
  end
end

これがあなたが探している説明であることを願っています:)

更新:私が言及するのを忘れていたのはPricesController、特定のストアがなくてもアクセスできるようにしたい場合(resources :prices上記で書いたので、そうしていると思います)、 aがハッシュ:store_idに指定されている場合はコントローラーをチェックインする必要があるということでしたparams、および指定されたストアなしでやりたいことを実行しない場合)

于 2012-05-16T20:54:22.757 に答える