2011-06-21 41 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

相关问题