2011-03-22 37 views
1

我试着写在轨道3的应用程序,我遇到了一些麻烦搞清楚了,我希望用户参加考试路线和控制器。这个应用程序的基本要求是:航线Rails3中 - 控制器和路线后第2个功能

  1. 用户,测试和问题都在不同的模型。
  2. 用户has_many测试。一个测试的has_many问题
  3. 提供的user_profile页面上的链接到/测试/新创建的测试记录。
  4. 提供的链接/测试/新/测试/:ID/part1的(其中:id是为test_id),使得用户可以完成测试的第一部分。问题将从数据库中检索并显示在此页面上。
  5. 提供通/测试/链接:ID/part1的到/测试/:ID /第2部分,使得用户可以完成测试的第二部分。再次,问题从数据库中检索。
  6. 提供上/测试/链接:ID/2部分提交测试,并返回到用户的个人资料。

我已经完成了模型,甚至通过他们的测试,所以我觉得我已经完成部分1和2

user.rb

Class User < ActiveRecord::Base 
    has_many :tests 
end 

test.rb

Class Test < ActiveRecord::Base 
    belongs_to :user 
    has_many :questions 
end 

question.rb

Class Question < ActiveRecrod::Base 
    belongs_to :test 
end 

当我尝试使用路线和控制器将这些模型放在一起时,我的问题就开始了。

的routes.rb

resources :users 

resources :tests do 
    member do 
    post 'part1' 
    post 'part2' 
    end 
end 

用户/ show.html.erb

<%= link_to "Start The Test", new_test_path %> 

测试/ new.html.erb

<%= link_to "Part 1", part1_test_path(@test) %> 

tests_controler.rb

class TestsController < ApplicationController 
    def new 
    @test = Test.new(current_user) 
    end 

    def part1 
    # still just a stub 
    end 
end 

我得到这个错误,当我点击链接参加测试的第1部分:

No route matches {:action=>"part1", :controller=>"tests", :id=>#<Test id: nil, taken_at: nil, user_id: nil, created_at: nil, updated_at: nil>} 

任何帮助,在此将不胜感激。

回答

2

通过定义它的预期的存在的测试,即在路线中的一员。一个被保存并拥有一个ID。

例如

part1_test_path = /test/123/part1 

你需要的是一个收集路线。

resources :tests do 
    collection do 
    post 'part1' 
    end 
    member do 
    post 'part2' 
    end 
end 

例如

part1_test_path = /test/part1 

编辑

建议解决方案:

resources :test, :path_names => { :new => 'part_1', :edit => 'part_2' } *1 

def new 
    @test = Test.new 

#new view 
form_for @test do 
    ... 

def create 
    @test = Test.new params[:test] 
    if @test.save 
    redirect_to edit_test_path @test 

def edit 
    @test = Test.find params[:id] 

#edit view 
form_for @test do 

def update 
    @test = Test.find params[:id] 
    if @test.update_attributes params[:test] 
    redirect_to test_path @test 


def show # test results 
    @test = Test.find params[:id] 
    if @test.incomplete *2 
    redirect_to edit_test_path @test 

* 1见rails guide on routing。这会给你像URL这样

测试/ part1的 测试/ 123/2部分

你应该把所有模型的验证;您对测试数据的要求。有条件验证是必需的,取决于它是否是new_record?或不,即如果你在第1部分或第2部分。

* 2 在你的模型中添加一个方法来检查测试的完整性。

def incomplete 
    self.some_test_field.blank? 

让我知道如果你什么都不懂。

+0

感谢您的答案马克。但是,这种解决方案不会给我part1和part1的不同路由(即part1_test_path =/test/part1和part2_test_path =/test/123/part2)吗?我希望在这些之间保持一致,以便代码库更易于维护。使用你的洞察力,成员期望一个存在的测试,我决定调用/ test/new页面上的创建控制器,然后尝试重定向到part1。看起来很有希望。 – spinlock 2011-03-22 18:52:16

+0

就我个人而言,我会采用我的方法,但你的方法同样有效。如果您还没有看过复杂表格,请查看这些专题节目。 http://railscasts.com/episodes/73它们用于rails 2,但除了一些适用于3的小语法之外。 – mark 2011-03-22 18:58:54

+0

感谢Mark。有什么关于你的方法会更符合“铁路方式”?我是新手,我想尽可能遵循规范风格,因为我正在计划将此应用程序交给其他开发人员,所以我试图尽可能遵循 - 并学习 - 约定。 – spinlock 2011-03-22 19:05:07