2012-06-04 52 views
0

我想修改的動作(提交)爲輔助的form_for的Rails的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 %> 

這是我的看法,它不工作。

所有我想要的是,我可以redirekt行動提交按鈕後,但隨後得到這個錯誤:

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' 

我在做什麼錯?

UPDATE

我所有的Funktion由助手的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 

回答

2

試試這個:

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

在URL中的@評估是提供一個零對象ID ,而且你還沒有身份證件。

如果你想分享創建和更新的形式,然後使用以下命令:

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

僅供參考,請查閱一軌的輸出產生支架的_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 
+0

以及我如何傳遞所有添加的信息?像價值和描述? – Lailo

+0

請問您可以添加一些更多的控制器代碼,我不看你的意思,問題是我的創建方法不創建與所有參數的評級對象。 – Lailo

+0

我已將「創建」操作添加到答案中。請嘗試。 – Anil