2011-06-21 23 views
0

我剛開始學習rails。我的rails版本是3.0.7。我想知道<%form_for:project_profile%><%form_for @project_profile%>之間有什麼區別。我有這個問題,因爲我走進了以下情況:form_for @project_profile和form_for之間有什麼區別:project_profile

  • 如果我使用<%的form_for:project_profile%>,它並沒有給我一個錯誤,但形式實際上是行不通的。

  • 如果我使用<%的form_for @project_profile%>,我會得到一個錯誤:未定義的方法`project_profile_path」爲#<#:0x00000103546d80>

  • 如果我使用<%=的form_for @project_profile ,:url =>「/ projects /#{params [:project_id]}/profile/update」do | f | %>,它會工作,但代碼是醜陋的。


您可以參考下面的代碼來了解我的問題的情況下更好。

我有一個項目模型和project_profile模型。一個項目有一個project_profile。

以下兩行來自我的routes.rb

match '/projects/:project_id/profile/edit' => "project_profiles#edit" 
match '/projects/:project_id/profile/update' => "project_profiles#update" 

這是從我project_profiles_controller.rb

class ProjectProfilesController < ApplicationController 
    def edit 
    @project_profile = Project.find(params[:project_id]).project_profile 
    end 
    def update 
    @project_profile = Project.find(params[:project_id]).project_profile 

    respond_to do |format| 
     if @project_profile.update_attributes(params[:project_profile]) 
     format.html {} 
     else 
     format.html { render :action => "edit" } 
     end 
    end 
    end 
end 

下面的代碼是從_form.html.erb

<%= form_for @project_profile, :url => "/projects/#{params[:project_id]}/profile/update" do |f| %> 
    <div class="field"> 
     <%= f.label :title %> 
     <br/> 
     <%= f.text_field :title %> 
    </div> 
    <div class="actions"> 
     <%= f.submit %> 
    </div> 
<% end %> 

回答

2

你應該學會有關資源和Rails的嵌套資源routing

您定義控制器的方式也不是常規的。在入門部分有一篇關於Rails指南的文章covers that

+0

很高興知道我的控制器不是傳統的。按照慣例幫助我繼續。 – ffmaer

相關問題