0

form_forヘルパーのアクション(送信)を変更したい

<%= form_for(@rating, :as => :post, :url => demo_create_rating_path(@rating)) do |f| %>
  <div class="field">
    <%= f.label :value %><br />
    <%= f.select :value, %w(1 2 3 4 5) %>
  </div>
    <%= f.hidden_field :article_id, :value => @article.id%>
    <%= f.hidden_field :user_id, :value => current_user.id %>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description, size: "100x5" %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

これは私のビューであり、機能しません。

私が望むのは、送信ボタンの後にアクションをリダイレクトできるが、このエラーが発生することだけです:

ActionController::RoutingError (No route matches {:controller=>"demo_ratings", :action=>"create", :article_id=>#<Rating id: nil, value: nil, description: nil, article_id: nil, user_id: nil, created_at: nil, updated_at: nil>}):
  app/views/demo_ratings/_form.html.erb:1:in `_app_views_demo_ratings__form_html_erb__1912848844925280312_70155649546120'
  app/views/demo_ratings/new.html.erb:13:in `_app_views_demo_ratings_new_html_erb__27525029454473720_70155632487040'

私は何を間違っていますか?

アップデート

form_for ヘルパーが必要とするすべての機能:

def new
    @rating = Rating.new
    @article = Article.find(params[:article_id])
  end

  def edit
    @rating = Rating.find(params[:id])
    @article = Article.find(params[:article_id])
  end

  def create
    @rating = Rating.new(params[:rating])
    if @rating.save
      @article= Article.find(params[:article_id])
      puts @article.name
      puts @rating.id
      @rating.article = @article
      puts @rating.article.name
      redirect_to demo_rating_path(@rating, :article_id => @article.id), notice: 'Rating was successfully created.'
    else
      render action: "new"
    end
  end

  def update
    @rating = Rating.find(params[:id])
    if @rating.update_attributes(params[:rating])
      @article = @rating.article
      redirect_to demo_rating_path(@rating), notice: 'Rating was successfully updated.'
    else
      render action: "edit"
    end
  end
4

1 に答える 1

2

これを試して:

<%= form_for(@rating, :as => :post, :url => demo_create_rating_path) do |f| %>

URLの@ratingはnilオブジェクトIDを提供しており、まだIDを持っていません。

作成と更新の間でフォームを共有する場合は、以下を使用します。

<% form_for(@rating, :as => :post) do |f| %>

参考までに、Railsで生成されたscaffoldの_form.html.erbの出力を確認してください。

コントローラでは、処理前に新しい/更新されたレコードを保存しています。ステートメントはのif @rating.save後に来る必要があります@rating.article = @article

  def create
    @rating = Rating.new(params[:post])
    @article= Article.find(params[:article_id])
    @rating.article_id = @article.id
    if @rating.save
      redirect_to demo_rating_path(@rating, :article_id => @article.id), notice: 'Rating was successfully created.'
    else
      render action: "new"
    end
  end
于 2012-06-04T13:36:47.943 に答える